Skip to Main Content
Blog

Concatenate two Arrays in Python

Concatenate two Arrays in Python

def main():
	"""
	Prints the result of two concatenated 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(",")))

	# Concatenate the lists
	c = a + b

	# Print the result
	print(c)


if __name__ == "__main__":
	main()
def main():
	"""
	Prints a merged list from two sorted 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(",")))

	# Merge the sorted lists
	c = merge(a, b)

	# Print the result
	print(c)


def merge(a: list[int], b: list[int]):
	"""
	Merges two sorted lists into one sorted list.
	"""

	c: list[int] = []

	# Merge the elements upto the shortest length
	a_index = 0
	b_index = 0
	while a_index < len(a) and b_index < len(b):
		if a[a_index] < b[b_index]:
			c.append(a[a_index])
			a_index += 1
		else:
			c.append(b[b_index])
			b_index += 1

	# Append the remaining elements of the first list
	while a_index < len(a):
		c.append(a[a_index])
		a_index += 1

	# Append the remaining elements of the second list
	while b_index < len(b):
		c.append(b[b_index])
		b_index += 1

	return c


if __name__ == "__main__":
	main()