A tuple is a collection of immutable Python objects. It can hold elements of any arbitrary data type (integer, string, float, list, etc.) which makes it a flexible and powerful data structure. It is a part of the Python core language and widely used in Python programs and projects.

Creating a Tuple

A tuple in Python can be created by enclosing all the comma-separated elements inside the parenthesis ().

        t1 = (1, 2, 3, 4)
t2 = ("Make", "Use", "Of")
t3 = (1.2, 5.9, 5.4, 9.3)

Elements of the tuple are immutable and ordered. It allows duplicate values and can have any number of elements. You can even create an empty tuple. A tuple's elements can be of any data type (integer, float, strings, tuple, etc.).

tuples-example-in -python

Creating an Empty Tuple

An empty tuple can be created by using empty opening and closing parentheses.

        emptyTuple = ()
    

Creating a Tuple With a Single Element

To create a tuple with only 1 element, you need to add a comma after the element to get it recognised as a tuple by Python.

         # t1 is a tuple
 t1 = ( 3.14, )
 print( type(t1) )
 # prints
 <class 'tuple'>
         # t2 is not a tuple
 t2 = ( 3.14 )
 print( type(t2) )
 # prints
 <class 'float'>

Note: type() Function returns the class type of the object passed as a parameter.

By not using a comma after the element results in the class type of t2 as ‘float’, thus it is mandatory to use a comma after the element when creating a tuple with a single value.

Creating a Tuple With Different Data Types

Elements of the tuple can be of any data type. This feature makes the tuple versatile.

        tup1 = ( 'MUO', True, 3.9, 56, [1, 2, 3] )
print( tup1 )
# prints
('MUO', True, 3.9, 56, [1, 2, 3])

Creating a Tuple Using tuple() Constructor

Tuples can also be created using the tuple() constructor. Using the tuple() constructor you can convert sequences like list/dictionary into a tuple.

        tup1 = tuple( (1, 2, 3) )
print( tup1 )
# prints
(1, 2, 3)

Creating a Nested Tuple

Tuples can easily be nested inside the other tuples. You can nest the tuple up to any level you want.

        tup1 = (1, 2, 3)
tup2 = ( 'Hello', tup1, 45 )
print( tup2 )
# prints
('Hello', (1, 2, 3), 45)

Accessing Elements in a Tuple

You can access tuple elements using index number inside the square brackets. Index number starts from 0. Tuple also supports negative indexing:

  • -1: points to the last element
  • -2: points to the second last element and so on
slicing-and-indexing-in-tuples
        tup1 = ('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
print( tup1[0] )
print( tup1[5] )
print( tup1[-1] )
print( tup1[-9] )
# prints
M
S
F
M

Slicing a Tuple

You can access a range of elements in a tuple using the colon : operator. Tuple also supports slicing operation using negative indexes.

        tup1 = ('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')

# Prints elements from index 1(included) to index 6(excluded)
print( tup1[1:6] )

# Prints elements from start to index 8(excluded)
print( tup1[:8] )

# Prints elements from index 3(included) to the end
print( tup1[3:] )

# Prints elements from index -4(included) to index -1(excluded)
print( tup1[-4:-1] )

# prints
('A', 'K', 'E', 'U', 'S')
('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O')
('E', 'U', 'S', 'E', 'O', 'F')
('S', 'E', 'O')

Checking if an Element Exists in a Tuple

You can check if an element exists in a tuple using the in keyword.

        tup1 = ('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
if 'M' in tup1:
    print("Yes, the element M exists in the tuple")
else:
    print("Element not found in the tuple !!")
 
# prints
Yes, the element M exists in the tuple

Updating Tuples

As tuples as immutable, it is not possible to change their value. Python throws a TypeError if you’ll try to update the tuple.

        tup1 = ('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
tup1[0] = 'Z'

# Following error is thrown
tup1[0] = 'Z'
TypeError: 'tuple' object does not support item assignment

But there is a hack if you want to update your tuple.

Change the Value of Elements of a Tuple Using Lists

You can change the value of elements in your tuple using lists in Python. First, you’ll have to convert the tuple to a list. Then modify the list as you want. Finally, convert the list back to a tuple.

        tup1 = ( 1, 2, 3 )
print( "This is the old Tuple: ")
print( tup1 )
temp = list( tup1 )
temp[0] = 4
tup1 = tuple( temp )
print( "This is the Updated Tuple: ")
print( tup1 )

# prints
This is the old Tuple:
(1, 2, 3)
This is the Updated Tuple:
(4, 2, 3)

Add New Elements in a Tuple Using Lists

Since tuples are unchangeable, it is not possible to add new elements in a tuple. Python will throw an error as:

        AttributeError: 'tuple' object has no attribute 'append
    

Again, you can use our hack (using lists) to deal with this. First, convert the tuple into a list. Then add new elements to the list. Finally, convert the list to a tuple.

Note: append() method is used in Python to add a new element to the end of the list.

        tup1 = ( 1, 2, 3 )
print( "This is the old Tuple: ")
print( tup1 )
temp = list( tup1 )
temp.append(4)
tup1 = tuple( temp )
print( "This is the Updated Tuple: ")
print( tup1 )

# prints
This is the old Tuple:
(1, 2, 3)
This is the Updated Tuple:
(1, 2, 3, 4)

Delete Operation on Tuples

As tuples are unchangeable, it is not possible to delete any element from the tuple. If you want to delete the complete tuple, it can be done using del keyword.

        tup1 = ( 1, 2, 3 )
del tup1

But you can use the same hack (using lists) as you used for changing and adding tuple items.

Deleting Elements From a Tuple Using Lists

Elements can be deleted from the tuple using lists in 3 simple steps:

Step 1: Convert the tuple into a list.

Step 2: Delete the elements from the list using the remove() method

Step 3: Convert the list into a tuple.

        tup1 = ( 1, 2, 3 )
print( "This is the old Tuple: ")
print( tup1 )
temp = list( tup1 )
temp.remove(1)
tup1 = tuple( temp )
print( "This is the Updated Tuple: ")
print( tup1 )

# prints
This is the old Tuple:
(1, 2, 3)
This is the Updated Tuple:
(2, 3)

Packing and Unpacking Tuples

While creating a tuple, values are assigned. This is called Packing a Tuple.

        # Example of packing a tuple
tup1 = ( 1, 2, 3)

Whereas extracting the values back into variables is called Unpacking a Tuple.

        # Example of unpacking a tuple
tup1 = ( 1, 2, 3 )
( one, two, three ) = tup1
print( one )
print( two )
print( three )

# prints
1
2
3

Looping With Python Tuples

Tuples are iterable containers just like lists in Python. You can easily loop through the tuple elements.

Using for Loop

Python's for loop works by iterating through the elements of the container.

        # Looping using for loop
tup1 = ( 1, 2, 3 )
for element in tup1:
    print( element )

# prints
1
2
3

Related: How to Use For Loops in Python

Using Index Numbers

You can iterate through the tuple using indexes of tuples. Use the len() function to find the size of the tuple.

        tup1 = ( 1, 2, 3 )
for index in range(len(tup1)):
    print( tup1[index] )
 
# prints
1
2
3

Improving Your Code Efficiency

Since the tuple data structure is immutable, its processing speed is faster than lists. Thus, it provides optimization to Python programs/projects. Using this powerful and versatile data structure (tuples) in your Python programs will take your code efficiency to the next level.