Using the + operator or zip function or itertools chain you can append multiple lists in Python. The + operator does a straightforward job of joining the lists together.
Append multiple lists of Python
Simple example code appends elements of 2-3 lists to one list.
l1 = [1, 3, 5, 5, 4]
l2 = [4, 6, 2, 8, 10]
l3 = [7, 5, 2, 9, 11]
# Using + operator
res1 = l1 + l2 + l3
print(res1)
# Using itertools.chain()
from itertools import chain
res2 = list(chain(l1, l2, l3))
print(res2)
# With zip
res_list = list(zip(l1, l2, l3))
print(res_list)
Output:
Is it possible to append multiple lists at once?
Answer: yes this is possible using the extend function.
x.extend(y+z)
or
x += y+z
or even
x = x+y+z
If you prefer a slightly more functional approach, you could try:
import functools as f
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
x = f.reduce(lambda x, y: x+y, [y, z], x)
Remember that using extend()
modifies the list in-place, while the +
operator creates a new list. Choose the method that best fits your requirements. If you want to keep the original lists unchanged, use the +
operator and assign the result to a new variable.
Comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.