
Concatenate lists in Python (extend, append, addition operator, slicing)
A Python list can be extended by extend()
, a list method.
x = ['a', 'b', 'c']
y = [1, 2]
x.extend(y)
print(x) # ['a', 'b', 'c', 1, 2]
print(y) # [1, 2]
It updates x
and takes only one list.
x = ['a', 'b', 'c']
y = [1, 2]
z = [3, 4]
x.extend(y, z)
# TypeError: extend() takes exactly one argument (2 given)
The difference of extend() and append()
extend()
may be confused with append(), which appends an element to a list. append()
adds an element but extend()
adds a list.
a = [1, 2, 3]
a.append(4)
print(a) # [1, 2, 3, 4]
The difference of extend() and addition operator
Python lists can be concatenated by +
operator.
a = [1, 2, 3]
b = [4, 5]
c = a + b
print(c) # [1, 2, 3, 4, 5]
The addition operator creates a new list and old lists doesn't change. List addition is a typical example of overloading operator.
Unpacking operator
a = [1, 2, 3]
b = [4, 5]
c = [*a, *b]
print(c) # [1, 2, 3, 4, 5]
*
is an unpacking operator that enables concatenating combined with brackets used to form a Python list.
extend() is equivalent to slicing
As stated in Python document, extend()
can be substituted with a slice format:
a = [1, 2, 3]
b = [4, 5]
a[len(a):] = b
print(a) # [1, 2, 3, 4, 5]
It's helpful to know list methods but it's also important to understand the equivalence of the iterable methods (like extend()
) and slice. append() is actually equivalent to this slice:
a = [1, 2, 3]
a[len(a):] = [5]
print(a) # [1, 2, 3, 5]
Comments
Powered by Markdown