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.
>>> 3 in tuple1
We can also concatenate tuples to create a new one using + or * operators:
>>> tuple1 = (1, 2, 3, 4)
>>> tuple_x2 = tuple1 + tuple1
(1, 2, 3, 4, 1, 2, 3, 4)
>>> tuple_x3 = tuple1 * 3
(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,)
>>> not_tuple = (2+5)
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
We can also use this feature to swap the values of two variables in a single line of code:
>>> x, y = y, x
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.
>>> tuple_from_list = tuple([1,2,3])
(1, 2, 3)
>>> list_from_tuple = list((4, 5, 6))
[4, 5, 6]
This article has covered some basic operations with tuples in Python.