Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Python Tuple – An Immutable Sequence

  • Python tuple is an immutable sequence.
  • The tuple is created with values separated by a comma.
  • Since a tuple is immutable, we can’t add or delete its elements.
  • If the tuple elements are not immutable, their properties can be changed. But, we can’t directly change a tuple element.
  • We can create nested tuples.
  • We can access tuple elements through their index. It also supports negative indexing to refer elements from the end to start.
  • We can also unpack tuple elements to comma-separated values.
  • Tuples are usually created to store heterogeneous elements. They can also have None.
  • Tuples support two operators: + for concatenation and * for repeating the elements.
  • Tuple supports slicing to create another tuple from the source tuple.
  • We can use “in” and “not in” operators with a tuple to check if the item is present in the tuple or not.
  • Since a tuple is a sequence, we can iterate over its elements using the for loop.
  • Python tuple class has two functionscount() and index().

How to Create a Tuple in Python?

We can create a tuple by placing all of its elements inside parentheses separated by a comma.

tuple_numbers = (1, 2, 3, 1)

We can keep different types of objects in a tuple.

tup = 1, 2, 3, 1, None, "Hello"

Let’s look at an example of a nested tuple.

nested_tuple = ((1, 2), ("Hello", "Hi"), "Python")

We can create an empty tuple by not having any element inside the parentheses.

empty_tuple = ()

The use of parentheses to create the boundary of a tuple is optional. However, it’s the best practice to use it. If you print a tuple, the elements are always printed inside the parentheses.

>>> tup = 1, 2, "Hello"
>>> print(tup)
(1, 2, 'Hello')
>>>

Creating a single item tuple is a bit tricky. If you place a single value inside the parentheses, it won’t create a tuple. It will create the object of the type of the value. Let’s check this behavior with a simple example.

single_item_tuple = ("Hello")

print(type(single_item_tuple))

single_item_tuple = (10)

print(type(single_item_tuple))

Output:

Python Tuple Example

We can add a comma after the value to create a tuple with a single element.

single_item_tuple = "Hello",

print(type(single_item_tuple))

single_item_tuple = 10,

print(type(single_item_tuple))
Python Tuple With Single Element
Python Tuple With Single Element

How to Access Tuple Elements?

We can access tuple elements through their index. The index value starts from 0 to the length of the tuple – 1.

tuple_numbers = (1, 2, 3, 4)

print(f'First element in tuple is {tuple_numbers[0]}')
print(f'Third element in tuple is {tuple_numbers[3]}')

If the tuple size is smaller than the specified index, “IndexError: tuple index out of range” is thrown.

>>> tuple_numbers = (1, 2, 3, 4)
>>> tuple_numbers[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>>

Tuple also supports negative indexing. In this case, the tuple element is retrieved from the end to the start. The negative index starts from -1 to the -(length of the tuple).

tuple_numbers = (1, 2, 3, 4)

print(f'Last element in tuple is {tuple_numbers[-1]}')
print(f'Second Last element in tuple is {tuple_numbers[-2]}')
print(f'First element in tuple is {tuple_numbers[-4]}')

If we have a nested tuple, we can access its elements through nested indexes.

>>> nested_tuple = (1, 2, (3, 4), (5, 6, 7))
>>> nested_tuple[2][0]
3
>>> nested_tuple[2][1]
4
>>> nested_tuple[3][0]
5
>>> nested_tuple[3][1]
6
>>> nested_tuple[3][2]
7
>>>

We can use negative indexes with the nested tuples too.

>>> nested_tuple = (1, 2, (3, 4), (5, 6, 7))
>>> 
>>> nested_tuple[-1][-1]
7
>>> nested_tuple[-2][1]
4
>>> nested_tuple[-2][-1]
4
>>> nested_tuple[3][-2]
6
>>> 

The below image shows how the indexes work in a tuple.

Python Tuple Index
Python Tuple Index

Slicing a Tuple

We can use slicing to create a subset of a tuple. This is useful in creating a new tuple from a source tuple. The slicing technique contains two indexes separated using a colon. The left index is included and the right index is excluded from the result.

tuple_numbers = (1, 2, 3, 4, 5, 6, 7, 8)

print(tuple_numbers[1:3])
print(tuple_numbers[:4])
print(tuple_numbers[5:])
print(tuple_numbers[:-5])

Output:

Slicing Tuple In Python
Slicing Tuple in Python

Tuple is immutable

A tuple is immutable in nature. So we can’t add, update or delete its elements. However, if the element is mutable then its properties can change.

>>> tup = (1,2)
>>> tup[0] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Let’s see an example where the tuple elements are mutable and we change their properties.

list_fruits = ["Apple"]

tup = ("Hello", list_fruits)

print(tup)

list_fruits.append("Banana")

print(tup)

Output:

Python Tuple With Mutable Elements
Python Tuple With Mutable Elements

Deleting a Tuple

We can’t delete elements of a tuple. But, we can delete the tuple itself using the del statement.

>>> tup = (1,2)
>>> print(tup)
(1, 2)
>>> del tup
>>> print(tup)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tup' is not defined
>>>

Tuple Concatenation (+ operator)

We can concatenate tuple elements to create a new tuple using the + operator.

>>> tuple1 = (1, 2)
>>> tuple2 = (3, 4)
>>> tuple3 = (5, 6, 7)
>>> 
>>> tuple_all = tuple1 + tuple2 + tuple3
>>> print(tuple_all)
(1, 2, 3, 4, 5, 6, 7)
>>> 

Repeating Tuple Elements (* operator)

Tuple also supports * operator to create a new tuple with the elements repeated the given number of times.

>>> tup = (1, 2, (3, 4))
>>> 
>>> tup1 = tup * 3
>>> 
>>> print(tup1)
(1, 2, (3, 4), 1, 2, (3, 4), 1, 2, (3, 4))
>>> 

Python Tuple Functions

The tuple class has two functions.

  1. count(x): returns the number of occurrences of the given element.
  2. index(x, start, end): returns the first index of the value. We can specify the start and end index to look for the value in the tuple. If the value is not found, ValueError is raised.
>>> tup = (1, 2, 3, 1, 2, 1, 3, 2, 1)
>>> 
>>> tup.count(1)
4
>>> tup.count(2)
3
>>> tup.index(2)
1
>>> tup.index(2, 2)
4
>>> tup.index(2, 2, 6)
4
>>> tup.index(20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>> 

Tuple Membership Test (in, not in operators)

We can check if the tuple contains an element using the “in” operator. Similarly, we can use “not in” operator to test if the element is not present in the tuple.

>>> vowels = ("a", "e", "i", "o", "u")
>>> 
>>> "a" in vowels
True
>>> "x" in vowels
False
>>> 
>>> "a" not in vowels
False
>>> "x" not in vowels
True

Iterating through a tuple

We can use for loop to iterate through the elements of a tuple.

vowels = ("a", "e", "i", "o", "u")

for v in vowels:
    print(v)

If you want to iterate through the tuple in the reverse order, you can use reversed() function.

for v in reversed(vowels):
    print(v)

Tuple vs List

  • A tuple is immutable whereas List is mutable.
  • The tuple is preferred over List to store different types of data types in a sequence.
  • Since a tuple is immutable, iterating through the tuple is slightly faster than a list.
  • A tuple is more memory and space-optimized than a List.
  • If you want to add, delete elements from a sequence then use List.

Python tuple() built-in function

We can also use the tuple() function to create a tuple. It accepts an iterable argument such as List and String. It’s useful in converting other sequence types to a tuple.

1. Python List to Tuple

list_numbers = [1, 2, 3]

tuple_numbers = tuple(list_numbers)
print(tuple_numbers)  # (1, 2, 3)

2. Python String to Tuple

s = "ABCD"
tuple_str = tuple(s)
print(tuple_str)  # ('A', 'B', 'C', 'D')

3. Python range to Tuple

r = range(1, 10)
tuple_range = tuple(r)
print(tuple_range)

Conclusion

A tuple is an immutable sequence in Python. When you want to have a read-only sequence, use a tuple.


References: