
10 Things You Should Know About Tuples in Python
Tuples are very handy to use in Python programming. Every Python programmer should know its usage really well.
As a general-purpose programming language, Python has become one of the most popular languages in various academic and industrial settings. Python has a powerful collection of data structures, such as int, string, list, dict, and tuple — an immutable sequence of data with a fixed size. This article reviews the most commonly used methods for the proper usage of tuples in Python.
1. Create a tuple using a sequence of values
To create a tuple, use commas to separate a sequence of values. The parentheses are optional, but they can improve readability especially when the declaration expression is not straightforward.
>>> tuple0 = 1, 4, 5
>>> print(tuple0)
(1, 4, 5)>>> tuple1 = (1, 2, 'three')
>>> print(tuple1)
(1, 2, 'three')>>> tuple2 = (4, 7, ('a', 'b'), lambda x: x+1)
>>> print(tuple2)
(4, 7, ('a', 'b'), <function <lambda> at 0x106e98830>)>>> tuple3 = ()
>>> print(tuple3)
()>>> tuple4 = 'one',
>>> print(tuple4)
('one',)Special cases are that we create an empty tuple using a pair of parentheses and a single-value tuple using a comma following the only value.
2. Create a tuple using tuple()
We can create tuples using the built-in tuple() method, which takes an iterable as its only argument. The generated tuple will be a sequence of the iterated items for the iterable. In the examples below, you can see what the tuples look like when generated from a str, dict, and list, respectively.
>>> tuple5 = tuple(['a', 'b'])
>>> print(tuple5)
('a', 'b')>>> tuple6 = tuple('tuple')
>>> print(tuple6)
('t', 'u', 'p', 'l', 'e')>>> tuple7 = tuple({'a': 1, True: 4})
>>> print(tuple7)
('a', True)>>> tuple8 = tuple((1, 'two', [1, 2]))
>>> print(tuple8)
(1, 'two', [1, 2])3. Count the number of elements in a tuple
As a tuple is a sequence, we can count the total number of all elements using len(). Another handy function count() can be used to count the number of a certain value that is specified in the call. See examples below.
>>> tuple_len = (1, 3, 'one', 'three', 'five')
>>> len(tuple_len)
5>>> tuple_count = (1, 1, 2, 2, 2, 2, 3, 3, 3)
>>> tuple_count.count(2)
4
>>> tuple_count.count(3)
34. Access tuple’s individual elements using index
After a tuple is created, we sometimes need to access some of their values. One way to do that is by using a 0-based index. Some examples are shown below. One thing that is worth noting is that in Python, we use negative numbers to index the sequence in reverse order. For example, -1 is the index for the last element in the sequence. Certainly, if we’re trying to access an element using an index outside the range, we’ll see the IndexError.
>>> tuple_index = (100, 'text', False, {1: 'five', 2: True})>>> tuple_index[0]
100>>> tuple_index[-1]
{1: 'five', 2: True}>>> tuple_index[2]
False>>> tuple_index[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range5. Access tuple’s individual elements using unpacking
Another concept that you may have often heard using tuples is tuple unpacking, which can allow access to individual elements. Some examples are given below.
>>> tuple_unpacking = (1, 'two', [3, 3, 3], {'four': 4})
>>> a, b, c, d = tuple_unpacking>>> a
1
>>> b
'two'
>>> c
[3, 3, 3]
>>> d
{'four': 4}6. Advanced tuple unpacking
Sometimes, when we unpack a tuple, we don’t need to access all individual elements. For those elements that we don’t care about, we can use an underscore (_) to indicate that. Another advanced tuple unpacking technique is that we can use the asterisk (*) to denote a sequence of elements in a tuple. The use of _ and * can be combined too.
>>> advanced_unpacking0 = (1, 2, 3)
>>> a, _, c = advanced_unpacking0
>>> a
1
>>> c
3>>> advanced_unpacking1 = (1, 2, 3, 4, 5, 11, 12, 13, 14, 15)
>>> a, *middle, c = advanced_unpacking1
>>> middle
[2, 3, 4, 5, 11, 12, 13, 14]
>>> _, *tail = advanced_unpacking1
>>> tail
[2, 3, 4, 5, 11, 12, 13, 14, 15]
>>> head, *_ = advanced_unpacking1
>>> head
17. Tuple concatenation
We can concatenate multiple tuples to create a new one using the plus (+) operator. Alternatively, if we want to create a new tuple by concatenating the same tuple for multiple times, we can use the multiplication (*) operator.
>>> concat_tuple0 = (1, 2) + ('three', 4) + ('five', 6)
>>> concat_tuple0
(1, 2, 'three', 4, 'five', 6)>>> concat_tuple1 = ('odd', 'event') * 4
>>> concat_tuple1
('odd', 'event', 'odd', 'event', 'odd', 'event', 'odd', 'event')8. Tuple immutability
As it’s mentioned at the beginning of this article, a tuple is an immutable sequence of values. Thus, we can’t change the values of individual elements.
>>> immut_tuple = (3, 5, 7)
>>> immut_tuple[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment9. Mutable elements
Although a tuple isn’t mutable as an object in its entirety, we are able to modify individual elements if they are mutable themselves. Some examples are shown below. Specifically, we modified the list and the dict in a tuple.
>>> mutable_elements = (1, [1, 2], {0: 'zero', 1: 'one'})>>> mutable_elements[1].append(3)
>>> mutable_elements
(1, [1, 2, 3], {0: 'zero', 1: 'one'})>>> mutable_elements[2][2] = 'two'
>>> mutable_elements
(1, [1, 2, 3], {0: 'zero', 1: 'one', 2: 'two'})10. Tuples in a for loop
We often need to use tuples in a for loop. As tuples are iterable, they can be used directly in a for loop, which will iterate through their individual elements. Alternatively, if we want to have a counter, we can use the built-in enumerate() method on the tuple. Some examples are given below.
>>> tuple_for_loop = ('one', 'two', 'three')
>>> for i in tuple_for_loop:
... print(i)
...
one
two
three>>> for (i, item) in enumerate(tuple_for_loop, start=1):
... print(str(i) + ': is ' + item)
...
1: is one
2: is two
3: is threeTuples are one of the favorite data structures I use in my Python programming, as they’re very convenient to construct and access individual elements. Certainly, please keep in mind that they’re immutable and don’t have too many methods, which may have limited their broader usage where you may consider using list or dict instead.






