Today we’ll be talking about operations on tuples and also some common functions that can be used with tuples. If you want to learn more about the basics of tuples, you can read this article. I also have an article about named tuples, if you are interested.
Here’s the video version of the article:
Table of Contents
Basic Operations
Slicing, concatenation and repetition work just like with any other sequence.
Slicing
>>> units = ("meter", "kilogram", "second", "newton", "volt", "joule")
We slice tuples just like lists. You can specify the start index, the past index and the step. Here’s an example with just the past index (which is exclusive). The start index is set to the default value of 0:
>>> print(units[:4])
('meter', 'kilogram', 'second', 'newton')
Concatenation
Let’s define another tuple:
>>> more_units = ("ampere", "watt")
Now let’s concatenate the two tuples:
>>> print(units + more_units)
('meter', 'kilogram', 'second', 'newton', 'volt', 'joule', 'ampere', 'watt')
Here’s another example:
>>> numbers = (1, 2, 3)
>>> numbers + (4, 5)
(1, 2, 3, 4, 5)
You can use the following syntax:
>>> numbers = numbers + (6,)
>>> numbers
(1, 2, 3, 6)
But you can also use the augmented assignment operator:
>>> numbers += (7, 8)
>>> numbers
(1, 2, 3, 6, 7, 8)
Repetition
Repetition works just like with lists:
>>> (1, 2, 3) * 5
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
Deleting a Tuple
Although it’s impossible to remove elements from a tuple, we can remove the whole tuple with del:
>>> scores = (8, 4, 6, 3, 2)
>>> del scores
If we now try to echo the tuple, we’ll get an error because the tuple doesn’t exist anymore.
>>> scores
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'scores' is not defined
The Membership Operators
You can use the membership operators to check whether an element is contained in the tuple or not:
>>> 5 in (1, 2, 7, 9)
False
>>> "a" not in ("p", "e")
True
Tuple Functions
You can use the same functions as with strings and lists. For example, you can check the length of a tuple using the len function:
>>> len(("ox", "pig", "cow"))
3
The max and min functions work just like with lists:
>>> numbers = (4, 8, 11, 5)
>>> syllables = ("ca", "to", "vee", "set", "am", "lit")
>>> min(numbers)
4
>>> min(syllables)
'am'
Here are two comma-separated elements not enclosed in (), [] or “”, so they default to a tuple:
>>> max(numbers), max(syllables)
(11, 'vee')