Sobes.tech
Junior

How to merge two arrays in Python?

sobes.tech AI

Answer from AI

  1. Operator +: Creates a new list by concatenating two lists.
  2. Method extend(): Adds elements of one list to the end of another list, modifying the original list.
  3. Operator *: Repeats a list, but not for merging two different lists.
  4. Methods append() and insert() in a loop: Add elements of one list to another one by one, inefficient for large lists.
  5. List of lists: Creates a new list containing the original lists as elements.
  6. Module itertools: Functions like chain(), 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.

How to merge two arrays in Python? — Python - sobes.tech