Append one list to another list in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Append one list to another list in Python #

To append one list to another list:

  1. Use the list.extend() method to append the elements of one list to another.
  2. Use the list.append() method to append an actual list object to another list.
main.py
# ✅ append the elements of one list to another list list_1 = ['bobby'] list_2 = ['hadz', 'com'] list_1.extend(list_2) print(list_1) # 👉️ ['bobby', 'hadz', 'com'] # --------------------------------------------- # ✅ append an actual list to another list list_1 = ['bobby'] list_2 = ['hadz', 'com'] list_1.append(list_2) print(list_1) # 👉️ ['bobby', ['hadz', 'com']]

The first example uses the list.extend() method to append the items of a list to another list.

main.py
list_1 = ['bobby'] list_2 = ['hadz', 'com'] list_1.extend(list_2) print(list_1) # 👉️ ['bobby', 'hadz', 'com']

The list.extend method takes an iterable and extends the list by appending all of the items from the iterable.

main.py
my_list = ['bobby'] my_list.extend(['hadz', '.', 'com']) print(my_list) # 👉️ ['bobby', 'hadz', '.', 'com']

The list.extend method returns None as it mutates the original list.

If you need to append an actual list to another list, use the list.append() method.

main.py
list_1 = ['bobby'] list_2 = ['hadz', 'com'] list_1.append(list_2) print(list_1) # 👉️ ['bobby', ['hadz', 'com']]

The list.append() method adds an item to the end of the list.

main.py
my_list = [] my_list.append(['bobby', 'hadz']) my_list.append(['.', 'com']) print(my_list) # 👉️ [['bobby', 'hadz'], ['.', 'com']]

The method returns None as it mutates the original list.

If you need to treat multiple lists as a single list, use the itertools.chain() class.

main.py
import itertools first = [1, 2] second = [3, 4] third = [5, 6] for item in itertools.chain(first, second, third): print(item) # 👉️ 1 2 3 4 5 6

The itertools.chain() class creates an iterator from the provided iterables.

The class is used for treating multiple sequences as a single sequence.

You can also use the addition (+) operator to append the elements of one list to another.

main.py
list_1 = ['bobby'] list_2 = ['hadz', 'com'] list_3 = list_1 + list_2 print(list_3) # 👉️ ['bobby', 'hadz', 'com']

When used with 2 lists, the addition (+) operator returns a new list that contains the elements of the two lists.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.