Python Tuples with examples

Introduction

Tuples are very similar to lists in Python, but in contrast to lists they can’t be modified. Once you created the tuple, you can’t modify/delete/append its elements, therefore tuples are said to be immutable.

How to create a tuple?

Similarly to a list, a tuple contains sequence of values. To create a tuple, we need to create a sequence of values enclosed by “(” and “)”. Most of the functions that apply to lists also apply to tuples , for example len(), max(), min(), slicing etc.

Example:

>>> tuple1[0]
1
>>> tuple1[2:]
(3, 4)
>>> min(tuple1)
1
>>> max(tuple1)
4
>>> len(tuple1)
4
>>> 3 in tuple1
True

We can also concatenate tuples to create a new one using + or * operators:

>>> tuple1 = (1, 2, 3, 4)
>>> tuple_x2 = tuple1 + tuple1
>>> tuple_x2
(1, 2, 3, 4, 1, 2, 3, 4)
>>> tuple_x3 = tuple1 * 3
>>> tuple_x3
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

How to create a one element tuple?

If you want to create a one element tuple you have to put a comma after that single element in a tuple, otherwise the Python will think that the expression in parentheses is just an expression to be evaluated, because parentheses in Python are used to change the order of operations, like in math. When we add a comma after the element it tells Python that parentheses are used to create a tuple. Example:

>>> tuple1 = (2+5,)
>>> type(tuple1)
<class 'tuple'>
>>> tuple1
(7,) >>> not_tuple = (2+5) >>> type(not_tuple) <class 'int'>
>>> not_tuple
7

Packing and unpacking tuples

Python allows us to pack and unpack tuples which means that we can use tuples on both sides of an assignment operator. For example, we can initialize multiple variables from a tuple like this:

>>> (a,b,c,d) = (1, 2, 3, 4)

Otherwise, we would have to write four lines of code to do it:

>>> a = 1
>>> b = 2
>>> c = 3
>>> d = 4

Python also accepts the following code, where parentheses are omitted. Although there are no parentheses, Python still uses tuple objects with the packing/unpacking feature behind the scenes to map the values to the variables:

>>> x, y, z = 10, 20, 30
>>> x
10
>>> y
20
>>> z
30

We can also use this feature to swap the values of two variables in a single line of code:

>>> x
10
>>> y
20
>>> x, y = y, x
>>> x
20
>>> y
10

How to create a tuple from a list and vice versa?

There’s a built-in function list() to create a list from a tuple. The function tuple() does the reverse and returns a tuple given a list.

Example:

>>> tuple_from_list = tuple([1,2,3])
>>> tuple_from_list
(1, 2, 3)
>>> list_from_tuple = list((4, 5, 6))
>>> list_from_tuple
[4, 5, 6]

Conclusion

This article has covered some basic operations with tuples in Python.

Tags:

Add a Comment