Concatenate or join two lists in Python

How to concatenate or join two lists using Python ?

This tutorial guides you on how to concatenate or join two lists using Python programming language.

Concatenate or join two lists using Python

Concatenate or join two lists in PythonThere are many ways using which you can concatenate or join two lists using Python programming. Let’s learn each approach with an example in the following sections.

Using + operator to join lists

You can use + operator to concatenate or join two lists as shown in the example below.

>>> list1 = [10,20,30]
>>> list2 = [11,22,33]

>>> final_list = list1 + list2 

>>> final_list
[10, 20, 30, 11, 22, 33]

But, the above solution will not work if there is a type mismatch and you will see TypeError as shown in the example below.

For example, let’s define the second list using range function.

>>> list1 = [1,2,3]
>>> list2 = range(4,6)

>>> final_list = list1 + list2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "range") to list

As you can see, that the above program resulted in error saying “can only concatenate list and no “range” to list. Therefore, you need to find an alternative way to join different type of lists.

Hence, from Python >3.5 there is another alternative approach called PEP 448 — Additional Unpacking Generalizations [*list1, *list2]. let’s see more details on how to use this approach to join two lists in the next section.

Additional Unpacking Generalizations [*list1, *list2]

The PEP 448 titled Additional Unpacking Generalizations has reduced some restrictions with respect to types or syntactic restrictions when we use * symbol with the Python expressions. Therefore, using this approach you can join two lists which are of different types.

For example, the second list uses range function and whereas the first one is list itself.

>>> list1 = [1,2,3]
>>> list2 = range(4,6)

>>> list1
[1, 2, 3]

>>> list2
range(4, 6)

>>> final_list = [*list1, *list2]

>>> final_list
[1, 2, 3, 4, 5]

using list.extend() method

It extends the sequence seq1 with the contents of sequence seq2.

The list.extend() iterates the list elements passed as an argument and add each element to the list. Therefore it results in extending the list and the length of the list increase by the number of elements that were iterated/ iterable in the argument.

>>> list1 = [1,2,3]
>>> list2 = range(4,6)

>>> list1.extend(list2)

>>> list1
[1, 2, 3, 4, 5]

That’s it. You had learnt numerous approaches to concatenate or join or combine lists using Python programming language.

Hope it helped 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments