Skip to Main Content
Blog

Sum Elements of Two Array in Python

Sum Elements of Two Array in Python

def main():
	"""
	Prints the result of two summed lists.
	"""

	# Read the lists from the user
	a = list(map(int, input("Enter list 1: ").split(",")))
	b = list(map(int, input("Enter list 2: ").split(",")))

	# Sum the elements of the lists
	c = sum_elements(a, b)

	# Print the result
	print(c)


def sum_elements(a: list[int], b: list[int]):
	"""
	Returns a list containing the sum of the elements of two lists.
	"""

	# Find the shortest and the longest list length
	min_length = min(len(a), len(b))
	max_length = max(len(a), len(b))

	# Create a list with the longest length
	merged = [0] * max_length

	# Sum the elements upto the shortest length
	for i in range(min_length):
		merged[i] = a[i] + b[i]

	# Copy the remaining elements of the first list
	if len(a) > min_length:
		for i in range(min_length, max_length):
			merged[i] = a[i]

	# Copy the remaining elements of the second list
	if len(b) > min_length:
		for i in range(min_length, max_length):
			merged[i] = b[i]

	return merged


if __name__ == "__main__":
	main()