pyt5
pyt5
To define a tuple in Python, we use parentheses () and separate the elements with a comma.
It is recommended to add a space after each comma to make the code more readable.
(1, 2, 3, 4, 5)
("a", "b", "c", "d")
(3.4, 2.4, 2.6, 3.5)
my_tuple = (1, 2, 3, 4, 5)
Tuple Indexing
>>> my_tuple[0]
1
>>> my_tuple[1]
2
>>> my_tuple[2]
3
>>> my_tuple[3]
4
>>> my_tuple[-1]
4
>>> my_tuple[-2]
3
>>> my_tuple[-3]
2
>>> my_tuple[-4]
1
Tuple Length
To find the length of a tuple, we use the len() function, passing the tuple as argument:
>>> len(my_tuple)
4
Nested Tuples
Tuples can contain values of any data type, even lists and other tuples. These inner tuples are
called nested tuples.
In this example, we have a nested tuple (4, 5, 6) and a list. You can access these nested
data structures with their corresponding index.
For example:
>>> my_tuple[0]
[1, 2, 3]
>>> my_tuple[1]
(4, 5, 6)
Tuple Slicing
We can slice a tuple just like we sliced lists and strings. The same principle and rules apply.
<tuple_variable>[start:stop:step]
For example:
>>> my_tuple[3:8]
(7, 8, 9, 10)
>>> my_tuple[2:9:2]
(6, 8, 10)
>>> my_tuple[:8]
(4, 5, 6, 7, 8, 9, 10)
>>> my_tuple[:6]
(4, 5, 6, 7, 8, 9)
>>> my_tuple[:4]
(4, 5, 6, 7)
>>> my_tuple[3:]
(7, 8, 9, 10)
>>> my_tuple[2:5:2]
(6, 8)
>>> my_tuple[::2]
(4, 6, 8, 10)
>>> my_tuple[::-1]
(10, 9, 8, 7, 6, 5, 4)
>>> my_tuple[4:1:-1]
(8, 7, 6)
Tuple Methods
>>> my_tuple.count(6)
2
>>> my_tuple.index(7)
5
💡 Tip: tuples are immutable. They cannot be modified, so we can't add, update, or remove
elements from the tuple. If we need to do so, then we need to create a new copy of the tuple.
Tuple Assignment
In Python, we have a really cool feature called Tuple Assignment. With this type of
assignment, we can assign values to multiple variables on the same line.
The values are assigned to their corresponding variables in the order that they appear. For
example, in a, b = 1, 2 the value 1 is assigned to the variable a and the value 2 is assigned
to the variable b.
For example:
# Tuple Assignment
>>> a, b = 1, 2
>>> a
1
>>> b
2
💡 Tip: Tuple assignment is commonly used to swap the values of two variables:
>>> a = 1
>>> b = 2
>>> a
2
>>> b
1