How to Join Lists in Python
In Python programming, combining two or more lists is a common task, particularly when working with data structures or aggregating input. This process, known as list concatenation, can be accomplished using several methods, each serving different purposes depending on the use case. This guide by Devyra explores the three most commonly used techniques: the +
operator, the append()
method, and the extend()
method.
1. Using the + Operator
The simplest way to merge two lists in Python is through the +
operator. This operator creates a new list by combining the contents of the original lists.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output: ['a', 'b', 'c', 1, 2, 3]
2. Using the append() Method with a Loop
Another approach involves iterating through one list and appending each element to the other. This method is suitable when you need to modify the original list in-place.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]
3. Using the extend() Method
The extend()
method offers a direct and efficient way to add the elements of one list to the end of another. Unlike append()
, which adds the list as a single element, extend()
integrates individual elements into the original list.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]