A 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 of same type or different and may be enclosed between parenthesis. Although, enclosing between parenthesis is recommended for readability purposes. Example,

empty_tuple = ()      # create empty tuple
enclosed_tuple = ("python", "language", 2018) # tuple enclosed between parenthesis
unenclosed_tuple = "python", "language", 2018 # tuple without parenthesis 
print(enclosed_tuple)       # prints ("python", "language", 2018)
print(unenclosed_tuple)     # prints ("python", "language", 2018)

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,

site_rank = ("google", 1, "facebook", 2)
print(site_rank[0])   # access first element, prints "google"
print(site_rank[-1])  # access last element, prints 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.
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.
Using len function of tuple: 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)   # prints 4
# using len method of tuple class
length = site_rank.__len__()
print(length)   # prints 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(countries[1:4])   # elements from index 1 to 4, that is, second to fourth element
print(countries[1:])    # all elements starting from second element
print(countries[-1:])   # all elements starting from last element
print(countries[-3:-1]) # elements from third last to second last position

Above code snippet prints the following output

(‘America’, ‘Spain’, ‘Australia’)
(‘America’, ‘Spain’, ‘Australia’, ‘England’)
(‘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")
name = employee[0]             # assigning name to a variable
age=  employee[1]              # assigning age to a variable
language = employee[2]         # assigning language to a variable
role = employee[3]             # assigning role to a variable
print(name + " is a " + role)  # prints "Dummy is a developer"

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") 
name, age, language, role = employee # unpacking a tuple 
print(name + " is a " + role)        # prints "Dummy is a developer"

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, a new element cannot be added to it, removed from it, neither can the 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")
employee[0] = "New Joinee"     # change the name of employee

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(employee)       # prints ("Dummy", 23, "python", "developer")
employee = ("New Joinee", employee[1], employee[2], employee[3])
print(employee)       # prints ("New Joinee", 23, "python", "developer")

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.


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.