Concatenating lists and tuples

Published

2023-07-31

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

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).