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.
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
.
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.
Sin_tuple =(10,)
Homogenous Tuple: A tuple with elements of the same datatype
str_tuple =('a','b','x','y')
Heterogeneous Tuple: A tuple with a collection of elements of varying data types.
mix_tuple= (6,'Sixty',6.5)
Nested Tuple: A tuple containing another tuple
nest_tuple=('prime',(1,2,3,5,7))
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 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 :
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.
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
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
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.
[m:n]
returns the subtuple from position m to n, but excluding index n.
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[1:4] =",T[1:4])
T[1:4] = ('Cow', 'Dog', 'Rat')
[:n]
returns the subtuple from starting position by default to n, but excluding index n.
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[:4] =",T[:4])
T[:4] = ('Cat', 'Cow', 'Dog', 'Rat')
[m:]
returns the subtuple from the position m to the ending index.
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[2:] =",T[2:])
T[2:] = ('Dog', 'Rat', 'Bat')
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[-4:-2] =",T[-4:-2])
Output:
T[-4:-2] = ('Cow', 'Dog')
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[:-2] =",T[:-2])
T[:-2] = ('Cat', 'Cow', 'Dog')
T= ('Cat','Cow','Dog','Rat','Bat')
print("T[-4:] =",T[-4:])
T[-4:] = ('Cow', 'Dog', 'Rat', 'Bat')
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.
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.
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])
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
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 :
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.
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.
(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.
(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)
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.
nest_tuple=('prime',(1,(2,(4,8)),3,5,7))
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.
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
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:
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 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 |
We have learned both tuple and list. Now let’s summarise important similarities and differences of python tuple and list.