Hello Technotizers,
in this article we will try to give you detailed information on Python – Tuples
and their methods. Tuples are used
to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuples, Sets and Dictionary all with different qualities and usage.
A tuple is a
collection which is ordered and unchangeable.
Tuples are written with round
brackets ().
city = ('Mumbai','Delhi','Chennai','Kolkata')
print(city)
The output is obtained
as:
('Mumbai', 'Delhi', 'Chennai',
'Kolkata'))
Some points
to be remembered:
·
Tuple items are
ordered, unchangeable, and allow duplicate values.
·
Tuple items are
indexed, the first item has index [0]
, the second item has index [1]
etc.
·
A tuples
item can be of any data type like int, string or Boolean. A tuple can also
contain items of mixed data types.
Examples:
All the below given tuples are valid in
Python.
tuple2 = (1, 4, 24, 14, 8)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")
·
The tuple() constructor:
It is
another way of creating a tuple.
city = tuple(('Mumbai','Delhi','Chennai','Kolkata'))
So now let’s move forward!!
·
Accessing tuple elements:
As seen in strings, Tuples items are
also accessed in the same way as in strings. Tuples items are indexed so they
can be accessed with the help of indexes. The indexing starts from 0 as usual.
Negative indexing means that the indexing begins from the end. -1 is the last
index, -2 the second last and so on. A range of indexes can also be specified
form where to start (inclusive) and where to end (exclusive).
city = ('Mumbai','Delhi','Chennai','Kolkata','Surat','Indore')
#referring index
print(city[0])
#negative indexing
print(city[-2])
#range of indexes
print(city[1:3])
#range of negative indexes
print(city[-2:-1])
The
output is obtained as:
Mumbai
Surat
('Delhi', 'Chennai')
('Surat',)
· Length of the Tuple:
To find the
length of the tuple, we will use the len() function
city = ('Mumbai','Delhi','Chennai','Kolkata','Surat','Indore')
print(len(city))
The
output is obtained as:
6
·
Identifying the Tuple by using type
function:
The Type
function describes about the nature of the that variable
For example to
identify the tuple we have to add a
comma after the item.
city = ('Mumbai')
print(type(city))
The
output is obtained as:
<class 'str'>
By adding comma after the item
city = ('Mumbai',)
print(type(city))
The
output is obtained as:
<class 'tuple'>
·
Update tuples:
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into
a list, change the list, and convert the list back into a tuple.
city = ('Mumbai','Delhi','Chennai','Kolkata')
city_list = list(city)
city_list[1] = 'Surat'
city = tuple(city_list)
print(city)
The
output is obtained as:
('Mumbai', 'Surat', 'Chennai', 'Kolkata')
Once a
tuple is created, you cannot add items to it.
city = ('Mumbai','Delhi','Chennai','Kolkata','Surat','Indore')
city.append('Panvel') # This will give a
error
AttributeError: 'tuple' object has no attribute 'append'. Since it is mutable and unchangeable so we can’t remove or add the items in the tuples.
Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.
city = ('Mumbai','Delhi','Chennai','Kolkata')
city_list = list(city)
city_list.append('Surat')
city = tuple(city_list)
print(city)
The
output is obtained as:
('Mumbai', 'Delhi', 'Chennai', 'Kolkata', 'Surat')
·
Remove tuple items:
Tuples are unchangeable, so you cannot remove items from it, but you can use the
same workaround as we used for changing and adding tuple items.
city = ('Mumbai','Delhi','Chennai','Kolkata')
city_list = list(city)
city_list.remove('Delhi')
city = tuple(city_list)
print(city)
The
output is obtained as:
('Mumbai', 'Chennai', 'Kolkata')
The
‘del’ keyword is used to entirely delete the tuple.
city = ('Mumbai','Delhi','Chennai','Kolkata')
del city
print(city)
#this will raise an error because the tuple no longer exists
·
Unpacking a tuple:
When we create a tuple, we normally assign values
to it. This is called "packing" a tuple. But, in Python, we are also
allowed to extract the values back into variables. This is called
"unpacking".
city = ('Mumbai','Delhi','Chennai','Kolkata')
(city1,city2,city3,city4)
= city
print(city1)
print(city2)
print(city3)
print(city4)
The
output is obtained as:
Mumbai
Delhi
Chennai
Kolkata
If the number
of variables is less than the number of values, you can add an *
to the variable name and the values will be
assigned to the variable as a list.
city = ('Mumbai','Delhi','Chennai','Kolkata')
(city1,city2,*city3) = city
print(city1)
print(city2)
print(city3)
The
output is obtained as:
Mumbai
Delhi
['Chennai', 'Kolkata']
If the
asterix is added to another variable name than the last, Python will assign
values to the variable until the number of values left matches the number of
variables left.
city = ('Mumbai','Delhi','Chennai','Kolkata')
(city1,*city2,city3) = city
print(city1)
print(city2)
print(city3)
The
output is obtained as:
Mumbai
['Delhi', 'Chennai']
Kolkata
·
Looping a tuple:
A for loop is used to loop through a
tuple. You can also loop through
the tuple items by referring to their index number. Use the range()
and len()
functions to create a suitable iterable.
city = ('Mumbai','Delhi','Chennai','Kolkata')
for i in city:
print(i,end=" ")
print('\n')
for i in range(len(city)):
print(city[i],end=" ")
The
output is obtained as:
Mumbai Delhi Chennai Kolkata
Mumbai Delhi Chennai Kolkata
The
len() method is used to get the length of a list.
To know
more about loops, refer the article Python-Loops
while
loop.
Use the len()
function
to determine the length of the tuple, then start at 0 and loop your way through
the tuple items by referring to their indexes. Remember to increase the index
by 1 after each iteration.
city = ('Mumbai','Delhi','Chennai','Kolkata')
i = 0
while i<len(city):
print(city[i],end=" ")
i = i+1
The
output is obtained as:
Mumbai Delhi Chennai Kolkata
·
Join Tuples:
One of
the easiest way to join tuples is using the + operator.
city = ('Mumbai','Delhi','Chennai','Kolkata')
numbers = (12,98,5,7,25)
print(city+numbers)
The
output is obtained as:
('Mumbai', 'Delhi', 'Chennai', 'Kolkata', 12, 98, 5, 7, 25)
If you want
to multiply the content of a tuple a given number of times, you can use the *
operator.
city = ('Mumbai','Delhi','Chennai','Kolkata')
city2 = city*2
print(city2)
The
output is obtained as:
('Mumbai', 'Delhi', 'Chennai', 'Kolkata', 'Mumbai', 'Delhi', 'Chennai',
'Kolkata')
·
Tuple methods:
Python offers two tuple methods given
below:
Method |
Description |
Returns
the number of times a specified value occurs in a tuple |
|
Searches
the tuple for a specified value and returns the position of where it was
found |
With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!
Keep coding and exploring new techs!!
Good Information!!
ReplyDeleteBest Python Online Training
Learn Python Online Course