A python tuple is a data structure which can hold similar or different item types. It is similar to a list in that it can hold items.
It is also different from list in that a tuple is immutable(or not mutable).
Being immutable means that once a tuple is created you cannot modify it by adding new items, removing exiting items, changing the values of existing items.
Second difference between a list and a tuple is in the syntax of their creation. A list is created using square brackets([ and ]) while a tuple is created using parenthesis. Also, the parenthesis are optional.

Creating a tuple
A tuple is created by declaring a variable and assigning it the items that it is supposed to contain.
Items may be of same type or different and may or may not be enclosed between parenthesis. Although, enclosing between parenthesis is recommended for readability purposes.
Example,

# create empty tuple
empty_tuple = ()      

# tuple enclosed between parenthesis
enclosed_tuple = ("python", "language", 2018) 

# tuple without parenthesis 
unenclosed_tuple = "python", "language", 2018 

# print tuples
print(empty_tuple)
print(enclosed_tuple)   
print(unenclosed_tuple)

This prints

()
(“python”, “language”, 2018)
(“python”, “language”, 2018)

A tuple is an object of class tuple. Hence, if you check the type of a tuple using type() function, you will get

<class ‘tuple’>

Accessing tuple elements
A tuple provides index based access to its elements where the index of first element is 0, second is 1 and so on. Indexing starts from left to right.
For accessing an element using its index, use the name of tuple followed by the index of element enclosed between square brackets([ and ]).

It is also possible to access elements from the right using negative indexes where the index of rightmost or last element is -1, second last element is -2 and so on.
Example,

# create a tuple
site_rank = ("google", 1, "facebook", 2)
# access first element
print('First element from left:',site_rank[0])
# access last element
print('First element from right:',site_rank[-1])

This prints

First element from left: google
First element from right: 2

Finding length of tuple
Length of a tuple means the total number of elements in a tuple. There are two ways of calculating the length of a tuple.

1. Using len function
Python’s inbuilt function len() can be used to calculate the length of a tuple. It takes the tuple as an argument and returns the length of the tuple.
2. Using len method
Tuple class also has a len method which returns the length of the tuple object on which it is invoked.

Both methods are shown below.

site_rank = ("google", 1, "facebook", 2)
# using inbuilt len function
length = len(site_rank)
print('Length using inbuilt len() function:',length)
# using len method of tuple class
length = site_rank.__len__()
print('Length using Tuple class len() method:',length)

Output of this code is

Length using inbuilt len() function: 4
Length using Tuple class len() method: 4

Notice that len method of tuple class is preceded and followed by two underscores.
Slicing a tuple
Slicing means accessing multiple elements of a tuple between a particular range such as from second to fifth elements or all elements starting from third element etc.

Syntax for slicing a tuple is by writing name of tuple followed by the indexes of range of elements required to be accessed separated by a colon(:) and enclosed between square brackets.
Elements are accessed starting from start index till end index – 1. Remember indexes are 0-based

Note that the first index should be less than the second one else no element will be selected since element selection is done in left to right direction.

It is also possible to slice elements from right end of the tuple. In this case negative indexes need to be used but again, first index should be less than the second index. Below examples will make it more clear,

countries = ("India", "America", "Spain", "Australia", "England")
print('Complete tuple=',countries)
# elements from index 1 to 4, that is, second to fourth element
print('countries[1:4]=',countries[1:4])
# all elements starting from second element
print('countries[1:]=',countries[1:])
# all elements starting from last element
print('countries[-1:]=',countries[-1:])
# elements from third last to second last position
print('countries[-3:-1]',countries[-3:-1])

Above code snippet prints the following output

Complete tuple= (‘India’, ‘America’, ‘Spain’, ‘Australia’, ‘England’)
countries[1:4]= (‘America’, ‘Spain’, ‘Australia’)
countries[1:]= (‘America’, ‘Spain’, ‘Australia’, ‘England’)
countries[-1:]= (‘England’,)
countries[-3:-1] (‘Spain’, ‘Australia’)

Unpacking a tuple
Many times individual elements of a tuple need to be assigned to variables so that they can be used separately. Example,

employee = ("Dummy", 23, "python", "developer")
# assigning name to a variable
name = employee[0]             
# assigning age to a variable
age=  employee[1]              
# assigning language to a variable
language = employee[2]         
# assigning role to a variable
role = employee[3]
print(name + " is a " + language +" " + role + " with age " + str(age))

which prints

Dummy is a python developer with age 23

This is suitable for smaller tuples but as the tuples become large or when this needs to be performed for multiple tuples, it becomes tedious and error prone since indexes are involved.
Python provides a short way of assigning values of tuple elements to variables using a single line where all variables corresponding to tuple elements are written at the left side and tuple is assigned to them at once.
Values of tuple elements are populated into the variables in the same order in which they are written. This is quite convenient and less error prone. Example,

employee = ("Dummy", 23, "python", "developer") 
# unpacking a tuple 
name, age, language, role = employee 
print(name + " is a " + language +" " + role + " with age " + str(age))

This outputs

Dummy is a python developer with age 23

Note that the number of tuple elements and the variables should exactly match else an error ValueError: too many values to unpack will be raised.

Immutability of tuple
A tuple once created cannot be modified. By modification means,
1. a new element cannot be added to it,
2. removed from it,
3. value of any of its element be modified.
When any of these operations is attempted an error is raised.

That is the reason, tuples do not have methods such as append, insert or remove as present in lists.
Consider the following example where value of a tuple element is modified.

employee = ("Dummy", 23, "python", "developer")
# change the name of employee
employee[0] = "New Joinee"

Above code when executed raises error, TypeError: ‘tuple’ object does not support item assignment.

Beating tuple immutability
Though value of a tuple element cannot be modified due to its immutability but a tuple variable can be assigned to another variable whose values are different.
It will then become a separate tuple as shown below

employee = ("Dummy", 23, "python", "developer")
print('Original employee:',employee)
employee = ("New Joinee", employee[1], employee[2], employee[3])
print('Updated employee:',employee)

Look how elements of previous tuple are accessed and assigned to the same tuple variable. This way the tuple is modified with the value of first element changed.

Still, no elements can be removed or added to a tuple. If you want a structure that would require addition and deletion of elements and modification of element values, then better go for a list.
Above code prints

Original employee: (‘Dummy’, 23, ‘python’, ‘developer’)
Updated employee: (‘New Joinee’, 23, ‘python’, ‘developer’)

which changes a value from existing tuple
Deleting tuple
A tuple can not be modified since it is immutable. This also means that you can not delete any of its elements.
But a tuple may be deleted entirely from scope using del keyword followed by the name of tuple.

When a tuple is deleted with del, it is removed as if it never existed and accessing the tuple after deleting raises an error. Example,

employee = ("Dummy", 23, "python", "developer")
# delete tuple
del employee
print(employee[0])

print(employee[0])
NameError: name ’employee’ is not defined

Hope this article helped you to learn python tuple.

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.