Junior
How to merge two arrays in Python?
sobes.tech AI
Answer from AI
- Operator
+: Creates a new list by concatenating two lists. - Method
extend(): Adds elements of one list to the end of another list, modifying the original list. - Operator
*: Repeats a list, but not for merging two different lists. - Methods
append()andinsert()in a loop: Add elements of one list to another one by one, inefficient for large lists. - List of lists: Creates a new list containing the original lists as elements.
- Module
itertools: Functions likechain(), for iterating over elements of multiple collections sequentially.
Examples:
# Operator +
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2 # [1, 2, 3, 4, 5, 6]
# Method extend()
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2) # list1 becomes [1, 2, 3, 4, 5, 6]
# List of lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list_of_lists = [list1, list2] # [[1, 2, 3], [4, 5, 6]]
# Module itertools.chain()
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list_iter = list(itertools.chain(list1, list2)) # [1, 2, 3, 4, 5, 6]
The most common and efficient ways to merge two lists are using the + operator or the extend() method, depending on whether you need a new combined list or want to modify one of the original lists. itertools.chain() is useful for merging many iterable objects.