Concatenating lists and tuples
Concatenating lists and tuples
Sometimes we have two or more lists or tuples, and we want to combine them. We’ve already seen how we can concatenate strings using the +
operator. This works for lists and tuples too!
>>> plain_colors = ['red', 'green', 'blue', 'yellow']
>>> fancy_colors = ['ultramarine', 'ochre', 'indigo', 'viridian']
>>> all_colors = plain_colors + fancy_colors
>>> all_colors
['red', 'green', 'blue', 'yellow', 'ultramarine', 'ochre',
'indigo', 'viridian']
or
>>> plain_colors = ('red', 'green', 'blue', 'yellow')
>>> fancy_colors = ('ultramarine', 'ochre', 'indigo', 'viridian')
>>> all_colors = plain_colors + fancy_colors
>>> all_colors
('red', 'green', 'blue', 'yellow', 'ultramarine', 'ochre',
'indigo', 'viridian')
This works just like coupling railroad cars. Coupling two trains with multiple cars preserves the ordering of the cars.
Answering the inevitable question: Can we concatenate a list with a tuple using the +
operator? No, we cannot.
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> [1, 2, 3] + (4, 5, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.