Python Tuples

A tuple is a data structure in Python that is a immutable (i.e. not modifiable), ordered sequence of elements. It allows duplicate items. Lists are defined by having elements between round brackets (). Each element in a tuple can be accessed separately, through indexing.

In Python programming, a tuple is similar to a list. The main difference between the two is that tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via indexing. Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list. Another difference is that since tuple are immutable, its elements can be used as key for a dictionary; while, this is not possible with a list.

Several operations may be performed on a Python tuple:~

1) Creation of a tuple:

To create a tuple in Python we have to put different comma-separated values between round brackets. It can have any number of items and they may be of different types (integer, float, string, list etc.). A nested tuple list can be created that even have another tuple as an item. It is also possible to use the tuple() constructor with double round-brackets to make a list. See the code below:

# tuple01.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
print(megacity_tuple)
mixed_tuple = (100, "motherland", [10, 20, 30], 15.3) # tuple with mixed data types
print(mixed_tuple)
nested_tuple = ("London", (0, 2, 4, 6, 8), ('X')) # nested tuple
print(nested_tuple)
country_tuple = tuple(("India", "China", "Russia", "America", "England")) # tuple() constructor
print(country_tuple)

Output:

('Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Chennai')
(100, 'motherland', [10, 20, 30], 15.3)
('London', (0, 2, 4, 6, 8), 'X')
('India', 'China', 'Russia', 'America', 'England')

 

2) Accessing elements of a tuple:

To access the tuple elements we have to refer to a specific index or a range of indices (called slicing) separated by a colon [x : y].  Python tuple allows negative indexing for its sequences like list. See the code below:

# tuple02.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
print(megacity_tuple[1])
print(megacity_tuple[2:5]) # 2nd to 4th position
print(megacity_tuple[1:]) # 1st to last position
print(megacity_tuple[-2]) # negative indexing
print(megacity_tuple[-4:-2]) # negative indexing with range

Output:

Mumbai
('Kolkata', 'Bengaluru', 'Chennai')
('Mumbai', 'Kolkata', 'Bengaluru', 'Chennai')
Bengaluru
('Mumbai', 'Kolkata')
 

3) Changing element of a tuple:

After a tuple is created, we cannot modify its values. Tuples are immutable:

# tuple03.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
megacity_tuple[3] = "Bangalore" # will raise an error
print(megacity_tuple)

Output:

ERROR
 

4) Looping through a tuple:

Using a loop through the elements of a tuple:

# tuple04.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
for item in megacity_tuple:
print(item)

Output:

Delhi
Mumbai
Kolkata
Bengaluru
Chennai
 

5) Length of a tuple:

It is easier to count the number of elements in a tuple using the len() method:

# tuple05.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
print(len(megacity_tuple))

Output:

5
 

6) To check if an element exists in a tuple:

To check if an element exists in a tuple we use the ‘in’ keyword:

# tuple06.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
item = "Chennai"
if item in megacity_tuple:
print("Yes, 'Chennai' is a megacity.")

Output:

Yes, 'Chennai' is a megacity.
 

7) Add an item to a list:

After a tuple is created, we cannot add elements to it. Tuples are immutable.

As this statement involving an assignment: “megacity_tuple[5] = “Patnacreates an error here, it is commented.

However, we can still use + operator to combine two tuples (of same type) into a new one, called concatenation. The * operator repeats a tuples for the given number of times. See the code below:

# tuple07.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
# megacity_tuple[5] = "Patna" # create an error
even_tuple = (0, 2, 4)
print(even_tuple + (6, 8))
print(("repeat", ) * 3) # comma (,) is a must

Output:

(0, 2, 4, 6, 8)
('repeat', 'repeat', 'repeat')
 

8) Remove a tuple:

​After a tuple is created, we cannot remove its values. Tuples are immutable.

However, we can use the ‘del’ keyword to delete a tuple completely:

# list08.py
megacity_tuple = ("Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai")
del megacity_tuple # don't try to print the tuple as it will show error