extend()Method to Append a List Into Another List in Python
chain()Function in the
itertoolsModule to Append Into a List in Python
Use the Concatenation
+Operator to Append Multiple Lists in Python
This tutorial will demonstrate ways to append a list into an already existing list in Python.
extend() Method to Append a List Into Another List in Python
Python has a built-in method for lists named
extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.
For example, declare two lists and add the second list into the main list using the method
lst = [4, 6, 8] lst2 = [10, 12, 14] lst.extend(lst2) print(lst)
[4, 6, 8, 10, 12, 14]
extend() method provides a straightforward way to append a list into an existing list with a simple function call.
chain() Function in the
itertools Module to Append Into a List in Python
itertools is a Python module containing fast and efficient utility methods for iterables. This module has the function
chain() that accepts a variable number of same-type iterables and concatenates them together in sequence based on the parameters.
We can use the
chain() function to append multiple lists and form them into a single list.
For this example, declare three different lists and set them as parameters for the
itertools.chain() function. We then wrap the function with another function
list(), which initializes a single list from the return value of the
import itertools lst = [9, 8, 7] lst2 = [6, 5, 4] lst3 = [3, 2, 1] lst_all = list(itertools.chain(lst, lst2, lst3)) print(lst_all)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
itertools.chain(), the parameters can be as many or as few as you want, and you will be provided with an efficient way of concatenating lists together and forming them into a single list.
Use the Concatenation
+ Operator to Append Multiple Lists in Python
Another simple method of appending multiple lists together is to use the
+ operator, which supports list concatenation in Python.
Simply perform the concatenation
+ operation on existing list variables, and the output will be a single combined list in order of the operands inputted in the code.
lst = [1, 3, 5] lst2 = [2, 4, 6] lst3 = [0, 0, 0] lst_all = lst + lst2 + lst3 print(lst_all)
[1, 3, 5, 2, 4, 6, 0, 0, 0]
In summary, three simple and efficient ways to append a list or multiple lists into a main list are extending, chaining, and using the concatenation
All three solutions perform reliably, and the comparative performance regarding time is relatively trivial, so it’s a matter of personal preference and convenience.