Python Tuples


August 23, 2021, Learn eTutorial
1144

In this python tutorial, you will master all about Python Tuples, Tuple creation, tuple indexing, and slicing, various tuple operators, and methods you ought to be acquainted with.

A tuple is a collection of well-ordered objects which are immutable in nature. Tuples are much similar to a list, both follow a sequence but the tuple does not support mutability of objects whereas the list support mutability. More specifically, we can’t change objects of a tuple once it is created though we can easily change objects in a list.

Key Features of Python Tuple

  • Tuples are immutable in nature
  • Tuples maintain the order of the objects
  • Tuples support indexing
  • Tuples can contain heterogeneous objects
  • Tuples are static
  • Tuples allow duplicate values

How to define Python Tuples

Defining a tuple in python is plain and simple just like a list. Python tuples are defined by enclosing a collection of well-ordered objects in parenthesis or a round bracket (). Each object is separated using commas ,.  Though parenthesis is optional, it is recommended for better coding and readability. Below examples that would be helpful to understand how to define python tuples in different ways.

Empty Tuple: A tuple with no elements or of length 0.

Example: Defining an empty tuple

emp_tuple =()
 

Singleton Tuple: A tuple with a single element. A singleton tuple is defined by enclosing a single element followed by a comma in parenthesis. Trailing comma is mandatory while defining a single element to pin down the fact that, this is a tuple, not an expression.

Example: Defining a singleton tuple

Sin_tuple =(10,)
 

Homogenous  Tuple: A tuple with elements of the same datatype

Example: Defining a Homogenous tuple

str_tuple =('a','b','x','y')
 

Heterogeneous Tuple: A tuple with a collection of elements of varying data types.

Example: Defining a Heterogeneous tuple with integer, string, and float datatypes

mix_tuple= (6,'Sixty',6.5)

Nested Tuple: A tuple containing another tuple

Example: Defining an nested tuple

nest_tuple=('prime',(1,2,3,5,7))

 

Indexing & slicing to access tuple elements

From the previous tutorials, we are familiar with indexing and slicing methods in python. In tuple, indexing and slicing is done in the same manner as in the list. we can access elements from tuple very easily using indexing and slicing.

Indexing in Python Tuple

Indexing is the process of assigning numbers to elements in a tuple for easy access. The index always starts with zero and must be an integer.

Two types of indexing in the python list are :

  • Positive Indexing  – indexing starts with 0 and traverses in the forwarding direction from head to tail.
  • Negative Indexing – indexing starts with -1 and traverses in a backward direction from tail to head.

To understand thoroughly about indexing let’s consider the example and its visualization. ‘T’ is a python tuple variable consisting of elements ‘cat’, ‘cow’,’ dog’ & ‘rat’. Each element in the tuple is assigned with a number corresponding to their position based on positive and negative indexing as shown below.

Python Tuple Indexing
  1. Getting elements through Positive indexing

    It is possible to access individual elements from a python tuple by referring to its index number. The below code shows how to access an item using positive indexing.

    Example: Getting a single element through positive indexing

    T= ('Cat','Cow','Dog','Rat')
    print('Element accessed at index 1 is:',T[1])
    print('Element accessed at index 3 is:',T[3]) 
    

    Output:

    Element accessed at index 1 is: Cow
    Element accessed at index 3 is: Rat
    
  2. Getting elements through Negative indexing

    Like the python list, the python tuple also supports negative indexing to access items from the tail. Negative indexing always starts from the end of the tuple with the index starting at -1.

    Example: Getting elements through negative indexing

    T= ('Cat','Cow','Dog','Rat')
    print('Element accessed at index -2 is:',T[-2])
    print('Element accessed at index -3 is:',T[-3]) 
    

    Output:

    Element accessed at index -2 is: Dog
    Element accessed at index -3 is: Cow
    

Slicing in Python Tuple

Python Tuple also functions well with range slice operator [:].Here, using the slice operator we can slice subsequences from a tuple as needed. In short, we can create a subtuple using the slice operator. The syntax for Range Slice is


T [ m:n]
 

where T is the tuple containing the items
m: starting index
n: ending index
T[m:n] returns the subtuple from the index m to n, but excluding the index n.
Slicing itself can be done in various ways with positive and negative indexing. Slicing can be best expressed by placing the items in the middle of indices as illustrated below.

Python Tuple Indexing

  1. Tuple Slicing through positive indexing

    • Slicing of the form :T[m:n] returns the subtuple from position m to n, but excluding index n.

      Example: How to slice tuple to get elements from m to n-1;

      T= ('Cat','Cow','Dog','Rat','Bat')
      print("T[1:4] =",T[1:4]) 
        
      Output:
      T[1:4] = ('Cow', 'Dog', 'Rat')
      
    • Slicing of the form :T[:n] returns the subtuple from starting position by default to n, but excluding index n.

      Example: How to slice tuple from starting position to nth position

      T= ('Cat','Cow','Dog','Rat','Bat')
      print("T[:4] =",T[:4]) 
        
      Output:
      T[:4] = ('Cat', 'Cow', 'Dog', 'Rat')
      
    • Slicing of the form : T[m:]  returns the subtuple from the position m to the ending index.

      Example: How to slice tuple from mth position to tail

      T= ('Cat','Cow','Dog','Rat','Bat')
      print("T[2:] =",T[2:]) 
        
      Output:
      T[2:] = ('Dog', 'Rat', 'Bat')
      

  2. Tuple Slicing through negative indexing

    • Slicing of the form :T[-m:-n] returns the subtuple from position m to n, but excluding index n.

      Example:How to slice a tuple from m to n using negative indexing

      T= ('Cat','Cow','Dog','Rat','Bat')
        print("T[-4:-2] =",T[-4:-2])

       

      Output:

      T[-4:-2] = ('Cow', 'Dog')
      
    •  Slicing of the form :T[:n]  returns the subtuple  from starting position by default to n,but excluding index n

      Example:How to slice a tuple from starting position to n using negative indexing

      T= ('Cat','Cow','Dog','Rat','Bat')
        print("T[:-2] =",T[:-2])

       

      Output:
      T[:-2] = ('Cat', 'Cow', 'Dog')
      
    • Slicing of the form: T[-m: ] returns the subtuple from the position m to the ending index.

      Example:How to slice a tuple from mth position to tail using negative indexing

      T= ('Cat','Cow','Dog','Rat','Bat')
        print("T[-4:] =",T[-4:])

       

      Output:
      T[-4:] = ('Cow', 'Dog', 'Rat', 'Bat')
      

How to modify Python Tuple

Immutability is one of the unique features of the datatype- tuple in the python programming language. To be more specific, we can’t change or modify elements in a tuple once it is created. That means it is not possible to add or replace or remove elements to or from a tuple. If we attempt to modify a tuple we will get a TypeError instead of output.

Example: Illustrating the property of tuple - Immutability


NT=('prime',[1,2,3,5,7])
NT[0]='ODD'
print(NT)
 

Output:


TypeError: 'tuple' object does not support item assignment

But the case is different when an element in a tuple is mutable. For instance, a tuple can contain a list as its element. The list is mutable and so that element can be modified. if you want to add one more prime number to the list we can add it as shown in the below example. The output will be an appended list with one more prime number 11.

Example: How to modify a mutable element with in a tuple


NT=('prime',[1,2,3,5,7])
NT[1].append(11)
print("Modified List in NT is :",NT)
 

Output:


Modified List in NT is : ('prime', [1, 2, 3, 5, 7, 11])

How to delete a tuple element

Considering the fact, a tuple is immutable, it is not possible to delete or remove an element from the tuple. However, we can delete the entire tuple using the keyword del. if we attempt to print a tuple after deletion NameError will be raised.

Example: How to delete a tuple

OT=(1,3,5,7,9)
del OT;
print(OT)
 

Output:


print(OT)
NameError: name 'OT' is not defined

How to pack and unpack python tuples

Literally, a python tuple is an assortment of different or same items in a well-fashioned order. We typically use assignment operator = to assign items on the right-hand side to a variable on the left-hand side. Python offers special features to enhance the assignment operator to another level.

They are :

Packing of Tuples

Example: How to pack tuples

T=('One','Two','Three','Four')
print("T[0] = ",T[0])
print("T[2] = ",T[2])
 

Output:


T[0] =  One
T[2] =  Three

Packing as its name indicates packs the collection of items to a single variable. The real-life example of packing clothes into a bag is much related to the packing of tuples. Packing can be well visualized as below.

Python Tuple Indexing

Unpacking of Tuples

Unpacking is just the opposite of packing where each item assigned to the tuple variable is unpacked to new tuples. Once again let’s consider the real-life example of unpacking clothes from a bag, where each clothes will be kept on designated shelves. Unpacking can be illustrated as below.

Python Tuple Indexing

Example: How to unpack tuples

(n1,n2,n3,n4) = T
print("n1 contains :",n1)
print("n2 contains :",n2)
print("n3 contains :",n3)
print("n4 contains :",n4)
 

Output:


n1 contains : One
n2 contains : Two
n3 contains : Three
n4 contains : Four

Python allows compound assignment by combining both packing and unpacking into a single statement. The format is shown in the example.

Example: Compound assignment of tuples

(n1,n2,n3,n4)= ('One','Two','Three','Four') 
print("n2 contains :",n2)
print("n3 contains :",n3)
 

Output:


n2 contains : Two
n3 contains : Three

One of the important points to be taken into consideration while unpacking is the number of variable objects on the left-hand side must be equal to a number of values in the tuple. If it fails ValueError will be outputted instead of the result.

ValueError while unpacking tuples


(n1,n2,n3) = T
(n1,n2,n3,n4,n5) = ('One','Two','Three','Four')
 

Output:


ValueError: too many values to unpack (expected 3)
ValueError: not enough values to unpack (expected 5, got 4)

What is a nested tuple in python?

Like a list, tuples also can be nested which means a tuple can contain another tuple as its element which may contain yet another tuple inside. We can define a nested tuple by placing the comma-separated elements inside () parenthesis.

Example: Defining a nested tuple


nest_tuple=('prime',(1,(2,(4,8)),3,5,7))
 

How to Access elements from a nested tuple

We can access elements from a nested tuple using indexing either positive or negative. The below example gives you the idea of getting elements from the nested tuple.

Example: Accessing elements from a nested tuple


nest_tuple=('prime',(1,(2,(4,8)),3,5,7))
#Positive indexing
print(nest_tuple[1])
print(nest_tuple[1][1])
print(nest_tuple[1][1][0])

#Negative indexing 
print(nest_tuple[-1])
print(nest_tuple[-1][-4])
print(nest_tuple[-1][-4][-1])

 

Output:


i = 10
f = 10.55 
C = -5-6i

Python Tuple Membership validation

The membership operator is used to validate the presence of an element or a sub tuple in the tuple. The corresponding result will be a truth value either True or False. Two membership operators in python are:

  • in: returns True if an element or sub tuple is present in the provided list
  • not in: returns True if an element or sub tuples is absent in the provided list.

T =('prime',1,3,5,7)
print("Validation 3 in tuple is ",3 in T)
print("Validation 8 not in List is",8 not in T)
 

Output:


Validation 3 in List is True
Validation 8 not in List is True

Python tuple Functions

Python tuple has some built-in functions to perform some usual sequential operations. The basic functions are tabulated below for easy reference.

Function Description
len(tuple) returns the length of the tuple.
max(tuple) returns the largest value among the tuple.
min(tuple) returns the smallest value among the tuple
compare(T1,T2) compares items in tuple T1 with items in tuple t2
list(seq) transforms list to a tuple

Python Tuple Vs Python List

We have learned both tuple and list. Now let’s summarise important similarities and differences of python tuple and list.

Similarity

  • Both tuple and list belongs to sequential Datatype
  • Both tuple and list can hold any types of elements
  •  Both can be accessed using indexing.

Difference

  • Tuples are immutable while the list is mutable
  • Tuples usually used to contain heterogeneous element while list usually contains homogenous items
  • Tuples are hashable hence can be used as an element in the set  while list are unhashable and can’t be used as an element in set
  • Tuples can be used as a key for a dictionary but the list can’t.
  • Tuples can’t be copies whereas a list can.
  • Tuples execute faster than a list