Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Concatenation

10.2.1

Concatenation

Concatenation joins tuples together using the + operator. Applying + to two tuples produces a longer tuple containing all the elements of the first followed by all the elements of the second. The result can be displayed directly or stored in a new tuple.

>>> odds  = (1, 3, 5, 7, 9)
>>> evens = (2, 4, 6, 8, 10)
>>> odds + evens              # concatenates the two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

The result of a concatenation can also be assigned to a new variable:

>>> primary   = ('Red', 'Green', 'Blue')
>>> secondary = ('Cyan', 'Magenta', 'Yellow', 'Black')
>>> palette = primary + secondary    # palette stores all seven colours
>>> palette
('Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black')

Extending a tuple with concatenation

Since tuples are immutable, there is no append operation — but the concatenation operator can be used to extend an existing tuple. Note what really happens: extending a tuple through concatenation creates a new tuple, which we then re-assign to the same name.

To add a single element, remember the single-element-tuple rule — the element must be written as a one-element tuple with a trailing comma:

>>> nums = (1, 2, 3, 4, 5)

# append a single element — note the (6,) form
>>> nums = nums + (6,)
>>> nums
(1, 2, 3, 4, 5, 6)

# append more than one element at once
>>> nums = nums + (7, 8, 9)
>>> nums
(1, 2, 3, 4, 5, 6, 7, 8, 9)
``` …