Tuples in Python

In this tutorial, I am going to discuss about Tuple datatype in python, different operations on tuples and methods available for manipulating tuples in python.

Tuples in Python

Tuple is another datatype collection like lists in python. It is also an ordered collection of python objects but lists and tuples are different because lists are mutable whereas tuples are immutable.

Creating a Tuple

A tuple is an arbitrary collection of python objects just like lists. The main difference between tuple and list is that list is enclosed within brackets ( [ ] ) and their elements and size can be changed whereas a tuple is enclosed within parentheses ( ( ) ) and cannot be updated.

Following is an example of tuple which contains objects of multiple datatypes.

tuple1 = (1, a, [2, 3], (b,c) )

Following table shows different type of tuple declarations in python :

Expression Description
T1 = ( ) Empty tuple
T2 = (10, 11, 12, 13) or ('e','f','g','h') A simple 4 item tuple
T3 = (22, 'new', (3, 'learn', 'value')) Nested tuples
T4 = tuple('Creating a Tuple') Tuple of an iterable item
T5 = tuple(range(3,15)) Tuple of successive integers from 3 to 14

The first 2 declarations are straight forward, first one is an empty tuple and second one is the simple tuple declaration with all elements of same datatypes.

The third expression is a nested tuple which means there is a tuple inside a tuple.

The fourth and fifth declaration shows how we can create a tuple using an iterable object in python.

Let's see some examples on creating a tuple.

tuple_ex = (1, 'a' , (2, 'b', 3, 'cde'))
print("Nested Tuple : ", tuple_ex)
print("Accessing an element from tuple inside a tuple : tuple_ex[2][1] - ", tuple_ex[2][1] )
tuple_ex2 = tuple("Coding Python")
print("Tuple from an iterable item : ",tuple_ex2)
tuple_ex3 = tuple(range(-5,10))
print("Tuple from range() function : ",tuple_ex3)
Nested Tuple :  (1, 'a', (2, 'b', 3, 'cde'))
Accessing an element from tuple inside a tuple : tuple_ex[2][1] -  b
Tuple from an iterable item :  ('C', 'o', 'd', 'i', 'n', 'g', ' ', 'P', 'y', 't', 'h', 'o', 'n')
Tuple from range() function :  (-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Accessing Elements in a Tuple

Tuples are ordered collections, so like lists tuple indices also start from 0. The indexing operator [ ] is used to access a single item present in the tuple at the index given as input.

To access a sub-part of the tuple slicing operator [ : ] can be used which takes two integers and gives the tuple within that indices.

Let's see some examples about accessing the elements of tuple in python.

tuple1 = ('first', 325, 13.24, 'tuples', 24, 'abc', 46)
tuple2 = (84, 'python')

print("tuple1 - ",tuple1)   #printing complete tuple
print("tuple1[0] - ",tuple1[0])   #printing first element of the tuple
print("tuple1[2:5] - ",tuple1[2:5])   #printing elements from 2 to 2 index in the tuple
print("tuple1[4:] - ",tuple1[4:])   #printing elements with index starting from 4
print("tuple1[-3:] - ", tuple1[-3:])  # printing all elements from second last element of the tuple.
print("tuple2[1][2] - ",tuple2[1][2])  #printing element of a nested iterable in a tuple
tuple1 -  ('first', 325, 13.24, 'tuples', 24, 'abc', 46)
tuple1[0] -  first
tuple1[2:5] -  (13.24, 'tuples', 24)
tuple1[4:] -  (24, 'abc', 46)
tuple1[-3:] -  (24, 'abc', 46)
tuple2[1][2] -  t

Traversing through a Tuple

Just like lists in python, we can use loops in python to traverse through a tuple. Recall that Traversing or iterating means accessing and processing each element of the sequence.

For Example the below shown example prints each element of a tuple.

tup1 = tuple("Learning Tuple")
for val in tup1 :
    print(val)
L
e
a
r
n
i
n
g

T
u
p
l
e

Thus by using loops, we can access and process each element of a tuple.

Python Tuple Operations

Just like python has different operations for lists and strings similarly python also has operations for tuples like concatenation, repetition and other.

Let's discuss about these operations on tuples one by one.

Concatenation Operation

Concatenating two tuples means joining two or more tuples to create a new tuple. It is performed using + operator in python. The + operator takes two tuples as operands and joins them together as output.

Let's see some examples :

tupl1 = (1,2,3)
tupl2 = (4,5,6)
new_tuple = tupl1 + tupl2
print("tupl1 : ", tupl1," tupl2 : ", tupl2)
print("tupl1 + tupl2 = ",new_tuple)
tupl1 :  (1, 2, 3)  tupl2 :  (4, 5, 6)
tupl1 + tupl2 =  (1, 2, 3, 4, 5, 6)

But we have to make sure that when + is used with tuples both the operands should be of list type, otherwise an error will be shown. For example :

tupl = tupl1 + 8
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-29-1586480a7a25 > in < module >
----> 1 tupl = tupl1 + 8

TypeError: can only concatenate tuple (not "int") to tuple

Repeating a Tuple

Just like with strings and lists, the * operator is used to repeat a tuple multiple number of times and create a new tuple.

It takes a tuple and a number as operands, the number is the number of times the tuple should be repeated. Just like + operator, the * operator also gives TypeError if we do not use an integer and a tuple as operands.

Let's see some examples below :

print("tupl1 : ",tupl1)
print("tupl1 * 3 = ",tupl1 * 3)
tupl1 :  (1, 2, 3)
tupl1 * 3 =  (1, 2, 3, 1, 2, 3, 1, 2, 3)

Membership Operation

We have discussed about membership operators in and not in while discussing about different operators in python.

These operators can be used with tuple operands to check if an element is present within a tuple.

Let's see the use of these operators with tuples in python.

print('a' in ('a','b','c'))
True
print(9 not in (9,8,7,6,5))
False

Slicing Operation

We know that we use slicing operator [ : ] in strings and lists to get sub-parts, similarly we can the slicing operator to get sub-part of a tuple. We can use the indices of tuple elements to create tuple slices.

Following is the syntax :
part = Tupl[ start : stop ].

In the syntax, start and stop refers to indices of the tuple elements which wish to include in the sub-part. Note that value present at the stop index is excluded from the sub-part.

We can use positive and negative integers as indices, here negative indices means that start from last element of a tuple towards first element of the same tuple. If the index given is not present in the tuple then we will get Index Error.

Let's see some examples :

tupl3 = (10, 'a', 65, 38, 42, 94, 'b', 'c', 85, 25)
print("tupl3[1:4] - ",tupl3[1:4])
print("tupl3[-3:] - ",tupl3[-3:])
print("tupl3[:2] - ",tupl3[:2])
print("tupl3[10] - ", tupl3[10]) 
tupl3[1:4] -  ('a', 65, 38)
tupl3[-3:] -  ('c', 85, 25)
tupl3[:2] -  (10, 'a')

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

< ipython-input-34-debeac8d7aed > in < module >
      3 print("tupl3[-3:] - ",tupl3[-3:])
      4 print("tupl3[:2] - ",tupl3[:2])
----> 5 print("tupl3[10] - ", tupl3[10])

IndexError: tuple index out of range

In the last example, IndexError is thrown because the tuple contains only 10 elements which means the tuple indices range from 0 to 9 hence 10th index is not present.

Tuple also supports another syntax of slice operator as shown below :

part2 = Tupl[ start : stop: step ]

In the above syntax start and stop have same meaning but a new step value is given to the slice operator. The step value means to skip that number of values while creating the tuple slice.

The default value for step is 1 but if we wish to increase the difference between the indices of the tuple slice then we can provide the value as step.

Let's understand this with example :

print("tupl3 = ", tupl3)
print("tupl3[0:9:4] = ",tupl3[0:9:4])
tupl3 =  (10, 'a', 65, 38, 42, 94, 'b', 'c', 85, 25)
tupl3[0:9:4] =  (10, 42, 85)

So, when we put the value of step as 4 we get every 4th element of the tuple from start to stop index.

Conversion to Tuple

Python provides tuple() method to convert different datatypes of python into tuple. The tuple() method takes an iterable python object like string, list or another tuple and then converts them into a tuple.

Let's see some examples :

tupl4 = tuple("Tuple Conversion")
tupl5 = tuple([1,2,3,4,5])
tupl6 = tuple(('a',1,'b',2,'c',3))
print(type(tupl4), tupl4)
print(type(tupl5), tupl5)
print(type(tupl6), tupl6)
< class 'tuple' > ('T', 'u', 'p', 'l', 'e', ' ', 'C', 'o', 'n', 'v', 'e', 'r', 's', 'i', 'o', 'n')
< class 'tuple' > (1, 2, 3, 4, 5)
< class 'tuple' > ('a', 1, 'b', 2, 'c', 3)

Tuple with single Element :

We have seen different types of tuples while creating tuples but what if we want to create a tuple with only a single number or character as an element. Let's see how to create tuple with only a single element :

tpl1 = ('a')
tpl2 = (1)
print(type(tpl1), tpl1)
print(type(tpl2), tpl2)
 a
 1

It seems like we are unable to create a single element tuple using simple parenthesis. Let's try using tuple() method :

tpl3 = tuple(2)
print(type(tpl3), tpl3)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-60-40cb300ea3d1 > in < module >
----> 1 tpl3 = tuple(2)
      2 print(type(tpl3), tpl3)

TypeError: 'int' object is not iterable

Observe that we get TypeError as the tuple() method only takes iterable python objects as argument.

To create a tuple with only single element we need to add a comma after the value in parenthesis. Let's see how to do that :

tpl4 = ('a',)
tpl5 = (1,)
print(type(tpl4), tpl4)
print(type(tpl5), tpl5)
< class 'tuple' > ('a',)
< class 'tuple' > (1,)

Tuple Methods in Python

There are different methods provided by python which are used with tuples for easy handling and processing of tuples.

Since tuple is an immutable object, we do not have any methods that add or remove elements from a tuple.

Tuple object supports some common methods like len(), min(), max(), sum() and sorted() which work similar as they work with lists.

There are only two methods provided for a tuple object in python which are count() and index(). Theses methods are also given for list objects and work in the same way. Let's see how :

tpl = (1,8,2,5,9,5,4,7)
print("length of tuple : len(tpl) - ",len(tpl))
print("minimun element of tuple : min(tpl) -",min(tpl))
print("count() method : ",tpl.count(5))
print("index() method : ",tpl.index(9))
length of tuple : len(tpl) -  8
minimun element of tuple : min(tpl) - 1
count() method :  2
index() method :  4

Tuple Manipulations

Although tuple is an immutable datatype, python also has some manipulations for tuples which we will discuss in this section.

Packing and Unpacking a Tuple

Creating a tuple from a set of values is known as packing. The reverse of packing i.e. creating individual values or variables from a tuple is called unpacking.

The unpacking is done as per given syntax :

var1, var2, var3 ... = tupl

In the above syntax var1, var2, var3 are variables which will get values from individual elements of the tuple tupl.

But make sure that number of variables on the left hand side should be exactly equal to the number of elements in the tuple otherwise ValueError will be shown.

We have seen examples of packing using tuple() method and using parenthesis ( ).

Let's understand unpacking of a tuple using examples :

tupl = (1,2,3)
a,b,c = tupl
print(type(a), a)
print(type(b), b)
print(type(c), c)
d,e,f,g = tup1
 1
 2
 1

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

< ipython-input-70-e6aea01d7c08 >  in < module >
      4 print(type(b), b)
      5 print(type(a), a)
----> 6 d,e,f,g = tup1

ValueError: too many values to unpack (expected 4)
a,b = tup
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

< ipython-input-71-1890bb844ccd > in < module >
----> 1 a,b = tup

ValueError: not enough values to unpack (expected 2, got 1)

Thus, if we use less or more number of variables than elements of the tuple while unpacking , we will get ValueError from python.

Immutability of Tuple

Tuples and lists are very similar collection datatypes, the only difference is that list is mutable ( or modifiable) and tuple is immutable ( or non-modifiable).

We have discussed about immutability in strings and the same thing applies to tuples.

Whenever we perform any operations like concatenation or repetition, python does not modify given tuple object but creates a new tuple object every time.

Even if we try to update a tuple using indexing operator, python will show TypeError.

This means that we cannot update or modify any element of tuple or the complete tuple.

tup = (1,2,3,4,5)
tup[0] = 0
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-88-de0d9e89495a > in < module >
      1 tup = (1,2,3,4,5)
----> 2 tup[0] = 0

TypeError: 'tuple' object does not support item assignment

In the above example, python throws TypeError as tuple object does not support item assignment.

Mutable Elements in Immutable Tuple

We know that we cannot modify elements of an immutable datatype like tuple, as it will throw TypeError as shown above.

But what if tuple contains a mutable datatype like list or dictionary as its element ? Can we modify elements of those mutable types ? Let's find out.

tup1 = (1,2,'a',[3,4,'b','cd'],'e',5,6)
print("Original tuple : ",tup1)
tup1[3][2] = 'new'
print("Tuple after change : ",tup1)
Original tuple :  (1, 2, 'a', [3, 4, 'b', 'cd'], 'e', 5, 6)
Tuple after change :  (1, 2, 'a', [3, 4, 'new', 'cd'], 'e', 5, 6)

In the above example, we can say that a mutable element inside an immutable object can be modified or updated.

As we know variables in python are labels associated with values or objects, so here when we change a mutable element inside an immutable object we are not changing the mutable python object but are changing its abstract value.

That is why we are able to change the value of an element inside a mutable element of an immutable object.

Indirectly Modifying a Tuple

As discussed tuples are immutable and hence we cannot change any element value of that tuple. But there are other ways using which we can update a tuple. Let's see how to do so.

1. Using Tuple Unpacking

We have discussed about unpacking a tuple into number of variables. We can use unpacking and packing of a tuple to modify elements of a tuple.

Let's see an example :

tup = (1,2,3)
print("Original tuple : ",tup)
a,b,c = tup
d = 4
b = 8
tup1 = (a,b,c,d)
print("After changing tuple : ",tup1)
Original tuple :  (1, 2, 3)
After changing tuple :  (1, 8, 3, 4)

2. Using Constructor functions

The functions used to convert values into a given datatype like int(), list() and tuple() are also known as constructor functions.
We can modify a tuple using constructor functions. Let's see how to do this using an example :

tup2 = (1,2,'a','b',3)
print("Original tuple : ",tup2)

# Convert tuple to list using list() method 
lst = list(tup2)
print("list = ",lst)

# Updating the list as needed
lst.append(4)
lst[0] = 'new'

#Convert list to tuple again
tup2 = tuple(lst)
print("Modified tuple : ",tup2)
Original tuple :  (1, 2, 'a', 'b', 3)
list =  [1, 2, 'a', 'b', 3]
Modified tuple :  ('new', 2, 'a', 'b', 3, 4)

Deleting a Tuple

Python has a keyword del, which is used to delete a python object. As you know, in python everything is an object including tuples. So, to delete a tuple we use this del keyword as shown in below example.

tup3 = (1,2,3,4,5)
print("Tuple = ",tup3)
del tup3
print(tup3) #Gives error as tup3 object is deleted.
Tuple =  (1, 2, 3, 4, 5)

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

< ipython-input-104-ac59fda69d79 > in < module >
      2 print("Tuple = ",tup3)
      3 del tup3
----> 4 print(tup3) #Gives error as tup3 object is deleted.

NameError: name 'tup3' is not defined
tupl4 = (1,2,3,'a','b','c',4,5,'de')
del tupl4[2]
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-106-4b6c45b995b1 > in < module >
      1 tupl4 = (1,2,3,'a','b','c',4,5,'de')
----> 2 del tupl4[2]

TypeError: 'tuple' object doesn't support item deletion

In the above example, we are not able to delete an entire tuple tup3 or particular item or element from the tuple tupl4. This again proves that tuples are immutable objects in python.

Conclusion

In this tutorial, we have discussed about tuple datatype in python. Creating and accessing a tuple, operations on tuples in python, built-in methods for tuples and tuple manipulations in python.

If you have any questions please comment below also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment