Python Tuples

In python, tuple is a collection of an ordered sequence of items to store the values of different data types. The tuple is the same as List, but the only difference is the Tuples are immutable that means once you create the tuple object, you are not allowed to make any changes to the tuple object.

 

In python, you can create the tuple by enclosing the items within parentheses ( )And the tuple items must be separated by commas.

 

Following is the example of creating the tuple with a different type of items in python.

 

# Tuple with integer types
a = (30, 10, 20)
# Tuple with string types
b = ("Suresh", "Rohini", "Trishi", "Hanshith")
# Tuple with mix types
c = (10, "Tutlane", 20)
# Empty Tuple
d = ()
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)

If you observe the above example, we created different tuple objects and printed the tuple object items using the python print method.

 

When you execute the above python tuple program, you will get the result as shown below.

 

a = (30, 10, 20)
b = ('Suresh', 'Rohini', 'Trishi', 'Hanshith')
c = (10, 'Tutlane', 20)
d = ()

Access Elements from Tuple

In python, you can access elements from the tuple object by using index values. In tuple, the index values will always start from 0. If your tuple object has 4 elements, you can access tuple elements using an index range 0 to 3.

 

Following is the example of accessing the elements from the tuple object in python.

 

tpl = (10, 20, 30, "Tutlane")
print(tpl[0])
print(tpl[2])
print(tpl[3])

If you observe the above example, we are accessing elements from tuple object using different index values with square brackets [ ].

 

When you execute the above python tuple example, you will get the result as shown below.

 

10
30
Tutlane

In python, you can also use negative indexing to access tuple object elements starting from the end. The index value -1 will refer to the last item, -2 refers to the second-last item, and so on.

 

Following is the example of accessing the elements from the tuple object using negative indexing in python.

 

tpl = (10, 20, 30, "Tutlane")
print(tpl[-1])
print(tpl[-2])
print(tpl[-4])

When you execute the above python tuple example, you will get the result as shown below.

 

Tutlane
30
10

If you try to access the elements from a tuple object that does not exist at the specified index, you will get an index error like “tuple index out of range”.

 

tpl = (10, 20, 30, "Tutlane")
print(tpl[5])
print(tpl[6])

If you observe the above example, the tuple object has only 4 elements that mean you can access the tuple elements using 0 to 3 index range. Still, we are trying to access the tuple object elements that don’t exist in the specified index range.

 

When you try to execute the above python tuple example, you will get an index out of range exception like as shown below.

 

Traceback (most recent call last):
  File "pythontuple.py", line 2, in <module>
    print(tpl[5])
IndexError: tuple index out of range

Access Range of Values from Tuple

In python, if you want to access the range of items from a tuple, you can use index ranging by specifying the starting and ending positions with the colon ( : ) operator. The index range will return a new tuple with the specified range of items.

 

The following is the example of accessing the specified range of elements from a tuple using a range of indexes in python.

 

tpl = (10, 20, 30, "tutlane", "learn", "python")
print(tpl[1:4])

When you execute the above python tuple example, you will get the result as shown below.

 

(20, 30, 'tutlane')

When you are slicing the tuple by defining the index range values, the search will start from the specified starting index position and end one item before the ending index position. The index positions will start from 0.

 

If you observe the above result, the tuple items slicing started from the index position 1 and stopped one item before the end index position 4.

 

It’s optional to define the starting and ending index positions in python to get the range of values from a tuple. If you skip mentioning the starting index position, the range will start from the first item the same way if you skip mentioning the ending index position, the range will continue to the end of the tuple.

 

Following is the example of getting the range of tuple items with or without specifying the starting and ending index of tuple items.

 

tpl = (10, 20, 30, "tutlane", "learn", "python")
# Without index values
print(tpl[:])
# Only starting index
print(tpl[2:])
# Only ending index
print(tpl[:5])

When you execute the above python tuple example, you will get the result as shown below.

 

(10, 20, 30, 'tutlane', 'learn', 'python')
(30, 'tutlane', 'learn', 'python')
(10, 20, 30, 'tutlane', 'learn')

You can also use negative indexing values in python to get the range of values from the tuple. Following is the example of getting the range of tuple elements using negative index values.

 

tpl = (10, 20, 30, "tutlane", "learn", "python")
print(tpl[-3:-1])
print(tpl[-4:-2])
print(tpl[-2:])

The above python tuple example will return the result as shown below.

 

('tutlane', 'learn')
(30, 'tutlane')
('learn', 'python')

Create Tuple with One Item

If you want to create a tuple object with one item, add a comma (,) after the item; otherwise, python will not consider it as a tuple object.

 

tpl = ("tutlane",)
print(type(tpl))

# Not a tuple
tpl1 = ("tutlane")
print(type(tpl1))

The above python tuple example will return the result as shown below.

 

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

Change Tuple Item Value

As discussed, tuples are immutable so, if you try to change the tuple object by modifying the existing values, you will get an exception like as shown below.

 

a = (30, 10, 20, "tutlane")
a[0] = 50
print("a = ", a)

If you observe the above example, we are trying to change the value of the tuple object. When you execute the above python program, you will get an exception like as shown below.

 

Traceback (most recent call last):
  File "D:\pythontuple.py", line 2, in <module>
    a[0] = 50
TypeError: 'tuple' object does not support item assignment

Still, there is a way to change or update the tuple object item values. To change the tuple item values first, you need to convert the tuple into a list, change/update the list item values, and convert the list back into a tuple.

 

Following is the example of converting the tuple into a list, change list items, and convert the list to a tuple in python.

 

tpl = (10, 20, 30, "tutlane", "learn")
print("Before: ",tpl)
lst = list(tpl)
lst[1] = 5
lst[3] = 40
lst[4] = 50
tpl = tuple(lst)
print("After: ",tpl)

When you execute the above python tuple example, you will get the result as shown below.

 

Before: [10, 20, 30, 'tutlane', 'learn']
After: [10, 5, 30, 40, 50]

Add or Append Items to Tuple

As discussed, tuple objects are immutable so, if you try to add new items to a tuple object, you will get a TypeError exception.

 

tpl = (10, 20, 30)
print("Before: ",tpl)
tpl[3] = 40
tpl[4] = 50
print("After: ",tpl)

The above python tuple example will return the result as shown below.

 

Traceback (most recent call last):
  File "D:\pythontuple.py", line 3, in <module>
    tpl[3] = 40
TypeError: 'tuple' object does not support item assignment

Remove Elements from Tuple

The tuple object is immutable, so it won’t allow you to remove the tuple elements, but by using the del keyword, you can delete the tuple completely.

 

Following is the example of using del keyword to delete the complete tuple object in python.

 

tpl = (10, 20, 30, "tutlane", "learn")
print("Before: ", tpl)
del tpl
print("After: ", tpl)

The above python tuple example will return the result as shown below.

 

Before:  (10, 20, 30, 'tutlane', 'learn')
Traceback (most recent call last):
  File "D:\pythontuple.py", line 4, in <module>
    print("After: ", tpl)
NameError: name 'tpl' is not defined

Tuple Length

In python, to count the number of items in the tuple, use the len() function.

 

Following is the example of using len() function in python to get the tuple length/size.

 

tpl = (10, 10, 20, 20, 30, "tutlane", "learn")
print("Tuple Size: ", len(tpl)) #Tuple Size: 7

By using len() function, you can also check whether the tuple is empty or not like as shown below.

 

tpl = ()
icount = len(tpl)
if icount > 0:
    print("Tuple size: ", icount)
else:
    print("Tuple is empty")

The above tuple example will return the result as shown below.

 

Tuple is empty

Join or Concatenate Tuples

In python, the + The operator is useful to join or concatenate multiple tuples and return a new tuple with all the tuples elements.

 

Following is the example of joining the tuples using + operator in python.

 

tpl1 = (10, 20, "tutlane")
tpl2 = (10, "learn", "python")
tpl3 = tpl1 + tpl2
print(tpl3)

The above tuple example will return the result as shown below.

 

(10, 20, 'tutlane', 10, 'learn', 'python')

Check If Item Exists in Tuple

By using in and not in operators, you can check whether the particular item exists in the tuple object or not.

 

Following is the example to verify whether the particular exists in the tuple or not using in operator in python.

 

tpl = (10, 20, 30, "tutlane", "learn")
print("20 in tuple: ", 20 in tpl)
print("tutlane in tuple: ", "tutlane" in tpl)
print("50 in tuple: ", 50 in tpl)

The above tuple example will return the result as shown below.

 

20 in tuple: True
tutlane in tuple: True
50 in tuple: False

Loop through a Tuple

By using for loop, you can loop through the items of tuple object based on your requirements.

 

Following is the example of looping through the tuple object items using for loop in python.

 

tpl = (10, 20, 30, "tutlane", "learn")
for item in tpl:
    print(item)

The above tuple example will return the result as shown below.

 

10
20
30
tutlane
learn

Remove Duplicates from Tuple

To remove duplicates from python tuple objects, you need to use the dictionary object fromkeys() method because we don’t have any direct method to remove duplicates from the tuple.

 

Following is the example of removing the duplicates from a tuple in python.

 

tpl = (10, 10, 20, 20, 30, "tutlane", "tutlane")
print("Before: ", tpl)
tpl = tuple(dict.fromkeys(tpl))
print("After: ", tpl)

Generally, the dictionary object will not allow duplicate keys. In the above example, we created a dictionary object by considering the tuple (tpl) items as keys. So, the dictionary object will automatically remove the duplicate keys. We converted the dictionary object to a tuple.

 

The above python tuple example will return the result as shown below.

 

Before: (10, 10, 20, 20, 30, 'tutlane', 'tutlane')
After: (10, 20, 30, 'tutlane')

Python Tuple Methods

In python, the tuple object has built-in methods to perform operations like a search for the specified value in the tuple and get the number of times a specified value occurs in the tuple.

 

Following are the built-in tuple methods available in the python programming language.

 

MethodDescription
count() It is useful to get the number of times the specified value occurs in the tuple.
index() It is useful to get the index position of the first occurrence of the specified value.

Following is the example of using Tuple methods in python.

 

tpl = (10, 10, 20, 20, 30, "tutlane", "tutlane")
x = tpl.count(20)
y = tpl.index(10)
print(x)
print(y)

The above python tuple example will return the result as shown below.

 

2
0