How we can iterate through list of tuples in Python
Last Updated :
26 Aug, 2022
In this article, we will discuss different ways to iterate the list of tuples in Python.
It can be done in these ways:
- Using Loop.
- Using enumerate().
Method 1: Using Loop
Here we are going to form a list of tuples using for loop.
Python3
name = [( 'sravan' , 7058 , 98.45 ),
( 'ojaswi' , 7059 , 90.67 ),
( 'bobby' , 7060 , 78.90 ),
( 'rohith' , 7081 , 67.89 ),
( 'gnanesh' , 7084 , 98.01 )]
for x in name:
for y in x:
print (y)
print ()
|
Output:
sravan
7058
98.45
ojaswi
7059
90.67
bobby
7060
78.9
rohith
7081
67.89
gnanesh
7084
98.01
Here we are going to use enumerate() function to Iterate the list of tuples. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.
Syntax: enumerate(iterable, start=0)
Parameters:
- Iterable: any object that supports iteration
- Start: the index value from which the counter is to be started, by default it is 0
Python3
name = [( 'sravan' , 7058 , 98.45 ),
( 'ojaswi' , 7059 , 90.67 ),
( 'bobby' , 7060 , 78.90 ),
( 'rohith' , 7081 , 67.89 ),
( 'gnanesh' , 7084 , 98.01 )]
l = []
for index, tuple in enumerate (name):
l.append(name[index])
for x in l:
for y in x:
print (y)
print ()
|
Output:
sravan
7058
98.45
ojaswi
7059
90.67
bobby
7060
78.9
rohith
7081
67.89
gnanesh
7084
98.01
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...