Tuples are immutable collection data structure in Python. They are very similar to lists except that we cannot modify the elements of a tuple, they are immutable.

Creating Tuples

We can create tuple using pair of parenthesis () or by using built-in function tuple(). The tuple function takes an iterable and converts that into a tuple of elements.

Example:

1()
2tuple()
3(1, 2, 3)
4tuple(range(2))
5tuple([1, 2, 3])

Tuples are an object of tuple class. We can check the type using type() function.

Example:

1numbers = (1, 2, 3)
2print(numbers) # (1, 2, 3)
3print(type(numbers)) # <class 'tuple'>

Tuples can also be of mixed data types. They can include numbers, strings or booleans in the same tuple.

1mixed_tuple = (1, 'Bob', True)

Tuples can also be nested just like Python lists.

1nested_tuple = (1, True, ("orange", "banana"))

If we want to create a tuple of single element, we have to append comma at the end of element to denote that this is list. If we don’t write comma, Python interpreter will create a string object.

1fruits = ('apple')
2print(type(fruits)) # str
3
4another_fruits = ('apple',)
5print(type(another_fruits)) # tuple

Output:

<class 'str'>
<class 'tuple'>

One more interesting fact about tuples is that while creating a tuple, we don’t explicitly have to wrap them in parentheses. Python will take list of comman separated elements and mark them as tuples.

1fruits = 'apple', 'orange', 'mango'
2print(type(fruits)) # <class 'tuple'>

Indexing

Tuple indexing works similar to lists. They are zero-indexed.

1numbers = (1, 2, 3, 4, 5)
2print(numbers[0]) # 1
3print(numbers[-1]) # 5
4
5nested_tuple = (1, True, ("orange", "banana"), 23)
6print(nested_tuple[2]) # ('orange', 'banana')
7print(nested_tuple[2][0]) # 'orange'

We can get the length of a tuple using len() function.

1numbers = (1, 2, 3, 4, 5)
2print(len(numbers)) # 5

Tuples are immutable. So, if we try to modify an element of a tuple, Python interpreter throws a TypeError.

1numbers = (1, 2, 3, 4, 5)
2numbers[4] = 500
TypeError: 'tuple' object does not support item assignment

Slicing

We can perform slicing operations like Python lists. Tuple slicing operation will return a new tuple with slice of elements from the original tuple. Again, the syntax for slicing looks like tuple[start:stop:step]. We can omit any of these three parts in slicing start, stop or step.

1fruits = ('apple', 'banana', 'mango', 'orange', 'pineapple')
2print(fruits[2:4]) # ('mango', 'orange')
3print(fruits[2:]) # ('mango', 'orange', 'pineapple')
4print(fruits[:3]) # ('apple', 'banana', 'mango')
5print(fruits[::-1])

Elements can be reversed by specifying negative value for step.

1print(fruits[::-1]) # ('pineapple', 'orange', 'mango', 'banana', 'apple')

Looping through Tuple Elements

Tuples are iterables like lists. So, we can iterate through elements of a tuple using simple for loops in Python.

Example:

1fruits = ('apple', 'banana', 'orange')
2for fruit in fruits:
3    print(fruit)

Output:

apple
banana
orange

If we want to also use index position of each element, we can use enumerate function which give tuple of each index and element.

Example:

1colors = ("white", "red", "blue", "brown")
2for index, color in enumerate(colors):
3    print(index, color)

Output:

0 white
1 red
2 blue
3 brown

Unpacking Tuples

We can unpack a tuple into multiple elements. This provides elegant syntax for variable assignment. In this make sure that the number of elements of a tuple on the right hand side matches the number of variables we want to assign on the left hand side.

Example:

1tup = (1, 2, "John")
2a, b, c = tup
3print(a, b, c) # 1 2 John

This method is also very useful when we want to return multiple values from a Python function. For example, below function returns sum and product of two numbers in the form of tuple.

Example:

1def sum_product(num1, num2):
2    return num1 + num2, num1 * num2
3
4sum, product = sum_product(2,4)
5print("Sum of 2 and 4 is {sum}".format(sum=sum))
6print("Product of 2 and 4 is {product}".format(product=product))

Output:

Sum of 2 and 4 is 6
Product of 2 and 4 is 8

This also provides neat trick to swap two numbers.

1num1 = 1
2num2 = 2
3print(num1, num2) # 1 2
4# Swap numbers
5num1, num2 = num2, num1
6print(num1, num2) # 2 1

Tuple Functions

There are few useful functions with tuple data structure. We can join two tuples using + operator and it will return elements of both tuples.

1numbers = (1, 2, 3)
2others = (4, 5, 6)
3numbers + others # (1, 2, 3, 4, 5, 6)

We can have elements of a tuple repeated specific number of times in a new tuple.

1numbers = (1, 2)
2numbers * 3 # (1, 2, 1, 2, 1, 2)

To find index position of a specific element in a tuple, we can use index() method. If the element exists, Python interpreter will return the index of that element. If the element does not exist, we get ValueError.

1fruits = "apple", "orange", "banana"
2fruits.index("banana") # 2
3fruits.index("peach") # ValueError: tuple.index(x): x not in tuple

We can use in operator to find if an element exists in a tuple. This returns boolean result True if element exists else False.

Example:

1numbers = tuple(range(1, 11, 2))
2print(numbers) # (1, 3, 5, 7, 9)
3print(3 in numbers) # True
4print(4 in numbers) # False
5
6fruits = ("apple", "banana", "grapes")
7"grapes" in fruits # True

We can find how many times a specific element occurs in a tuple using count() method.

1numbers = (1, 2, 3, 7, 4, 3)
2print(numbers.count(3)) # 2

We can delete complete tuple using del operator.

1numbers = (1, 2, 3)
2del numbers # remove the tuple from memory