## Tuples

Tuples are sequences which work just like lists the only difference is that they are immutable which means we can’t add, remove or modify it’s elements once it is created. This also makes them super efficient in comparison to list. Tuples are used to store list of items which don’t change.

## Creating Tuples

Tuples can be created by listing elements separated by comma (`,`

) inside a pair of parentheses i.e `()`

. Here are some examples:

1 2 3 4 5 6 7 8 9 | >>> >>> t = ("alpha", "delta", "omega") >>> >>> t ('alpha', 'delta', 'omega') >>> >>> type(t) <class 'tuple'> >>> |

Here is how we can create an empty tuple:

1 2 3 4 5 6 7 8 | >>> >>> et = () # an empty tuple >>> et () >>> >>> type(et) <class 'tuple'> >>> |

We can also use constructor function i.e `tuple()`

, which accepts any type of sequence or iterable object.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | >>> >>> t1 = tuple("abcd") # tuple from string >>> >>> t1 ('a', 'b', 'c', 'd') >>> >>> >>> t2 = tuple(range(1, 10)) # tuple from range >>> >>> t2 (1, 2, 3, 4, 5, 6, 7, 8, 9) >>> >>> >>> t3 = tuple([1,2,3,4]) # tuple from list >>> t3 (1, 2, 3, 4) >>> |

List comprehension can also be used to create tuples.

1 2 3 4 5 | >>> >>> tlc = tuple([x * 2 for x in range(1, 10)]) >>> tlc (2, 4, 6, 8, 10, 12, 14, 16, 18) >>> |

To create a tuple with just one element, you must type the trailing comma after the value, otherwise it will not be a tuple. For example:

1 2 3 4 5 6 7 8 9 10 | >>> >>> t1 = (1,) # this is a tuple >>> type(t1) <class 'tuple'> >>> >>> >>> t2 = (1) # this is not >>> type(t2) <class 'int'> >>> |

The use of parentheses to enclose the elements of a tuple is optional. It means we can also create tuples like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> >>> t1 = "alpha", "delta", "omega" # t1 is a tuple of three elements >>> t1 ('alpha', 'delta', 'omega') >>> type(t1) <class 'tuple'> >>> >>> >>> t2 = 1, 'one', 2, 'two', 3, 'three' # t2 is a tuple of six elements >>> t2 (1, 'one', 2, 'two', 3, 'three') >>> type(t2) <class 'tuple'> >>> |

Notice that, although we didn’t use parentheses while creating tuples, Python uses them while printing tuples.

Just as before, to create a tuple with one element trailing comma (`,`

) after the value is required.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> >>> t1 = 1, >>> t1 (1,) >>> type(t1) <class 'tuple'> >>> >>> >>> t2 = 1 >>> t2 1 >>> type(t2) <class 'int'> >>> |

We will use parentheses explicitly while creating tuples. However, the other form also has its uses, most notably while returning multiple values from a function.

## Tuple Unpacking

Tuples let you assign values to multiple variables at once. For example:

1 2 3 4 5 6 7 8 9 10 | >>> >>> first, second, third = ("alpha", "beta", "gamma") >>> >>> first 'alpha' >>> second 'beta' >>> third 'gamma' >>> |

This is known as Tuple Unpacking. The number of variables (on left side) and the number of elements in the tuple (on right side) must match otherwise you will get an error.

1 2 3 4 5 6 7 8 9 10 11 12 | >>> >>> first, second, third, fourth = ("alpha", "beta", "gamma") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 3 values to unpack >>> >>> >>> first, second, third = ("alpha", "beta", "gamma", "phi") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 3) >>> |

Since the parentheses is optional, the above code can also be written as:

1 2 3 4 5 6 7 8 9 10 | >>> >>> first, second, third = "alpha", "beta", "gamma" >>> >>> first 'alpha' >>> second 'beta' >>> third 'gamma' >>> |

Recall that we have already learned about this in Lesson Data Types and Variables In Python, under the title Simultaneous Assignment. Well, now you know behind the scenes we were using tuples unknowingly!

## Operations on Tuples

A tuple is essentially an immutable list. As a result, most of the operations that can be performed on the list are also valid for tuples. Here are some examples of such operations:

- Access a single element or slices of elements using
`[]`

operator. - built-in functions like
`max()`

,`min()`

,`sum()`

are valid on a tuple. - Membership operator
`in`

and`not in`

. - Comparison operators to compare tuples.
`+`

and`*`

operators.- for loop to iterate through elements.

and so on.

Whenever you are facing a dilemma whether an operation is valid for a tuple or not, just try it out in the Python Shell.

The only type of operations which tuple doesn’t support are the ones that modify the list itself. Therefore methods such as `append()`

, `insert()`

, `remove()`

, `reverse()`

and `sort()`

don’t work with tuples.

The following program demonstrates some common operations that can be performed on tuples.

*python101/Chapter-20/operations_on_tuple.py*

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | tuple_a = ("alpha", "beta", "gamma") print("tuple_a:", tuple_a) print("Length of tuple_a:", len(tuple_a)) # len() function on tuple tuple_b = tuple(range(1,20, 2)) # i.e tuple_b = (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) print("\ntuple_b:", tuple_b) print("Highest value in tuple_b:", max(tuple_b)) # max() function on tuple print("Lowest value in tuple_b:",min(tuple_b)) # min() function on tuple print("Sum of elements in tuple_b:",sum(tuple_b)) # sum() function on tuple print("\nIndex operator ([]) and Slicing operator ([:]) : ") print("tuple_a[1]:", tuple_a[1]) print("tuple_b[len(tuple_b)-1]:", tuple_b[len(tuple_b)-1]) print("tuple_a[1:]:", tuple_a[1:]) print("\nMembership operators with tuples: ") print("'kappa' in tuple_a: ",'kappa' in tuple_a) print("'kappa' not in tuple_b: ",'kappa' not in tuple_b) print("\nIterating though elements using for loop") print("tuple_a: ", end="") for i in tuple_a: print(i, end=" ") print("\ntuple_b: ", end="") for i in tuple_b: print(i, end=" ") print("\n\nComparing tuples: ") print("tuple_a == tuple_b:", tuple_a == tuple_b) print("tuple_a != tuple_b:", tuple_a != tuple_b) print("\nMultiplication and addition operators on tuples: ") print("tuple * 2:", tuple_a * 2) print("tuple_b + (10000, 20000): ", tuple_b + (10000, 20000)) |

**Output:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | tuple_a: ('alpha', 'beta', 'gamma') Length of tuple_a: 3 tuple_b: (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) Highest value in tuple_b: 19 Lowest value in tuple_b: 1 Sum of elements in tuple_b: 100 Index operator ([]) and Slicing operator ([:]) : tuple_a[1]: beta tuple_b[len(tuple_b)-1]: 19 tuple_a[1:]: ('beta', 'gamma') Membership operators with tuples: 'kappa' in tuple_a: False 'kappa' not in tuple_b: True Iterating though elements using for loop tuple_a: alpha beta gamma tuple_b: 1 3 5 7 9 11 13 15 17 19 Comparing tuples: tuple_a == tuple_b: False tuple_a != tuple_b: True Multiplication and addition operators on tuples: tuple * 2: ('alpha', 'beta', 'gamma', 'alpha', 'beta', 'gamma') tuple_b + (10000, 20000): (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 10000, 20000) |