Skip to content

Computer Science · Ch 9 — Lists

Concatenation

9.2.1

Concatenation

Python joins two or more lists using the concatenation operator, written with the symbol +. The result is a single new list containing the elements of the first list followed by the elements of the second.

Joining lists with +

# multiples of 5 and multiples of 7
>>> fives = [5, 10, 15, 20, 25]
>>> sevens = [7, 14, 21, 28, 35]

# elements of fives followed by elements of sevens
>>> fives + sevens
[5, 10, 15, 20, 25, 7, 14, 21, 28, 35]

It works just as well for lists of strings:

>>> weekdays = ['Mon', 'Tue', 'Wed']
>>> weekend = ['Sat', 'Sun']
>>> weekdays + weekend
['Mon', 'Tue', 'Wed', 'Sat', 'Sun']

Concatenation does not change the original lists

A crucial point: after the + operation, the operand lists are unchanged — fives, sevens, weekdays and weekend above all keep their original contents. Concatenation only produces a combined list; it does not store it anywhere by itself.

If you actually want to keep the merged list, use an assignment statement to capture the result in a variable:

>>> alldays = weekdays + weekend
>>> alldays
['Mon', 'Tue', 'Wed', 'Sat', 'Sun']

Both operands must be lists

The + operator for concatenation requires that both operands are of list type. Trying to concatenate a list with a value of some other data type — a string, a number, and so on — raises a TypeError:

>>> nums = [1, 2, 3]
>>> word = "xyz"
>>> nums + word
TypeError: can only concatenate list (not "str") to list
``` …