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
# create a list of tuples with student# detailsname = [('sravan',7058,98.45),        ('ojaswi',7059,90.67),        ('bobby',7060,78.90),        ('rohith',7081,67.89),        ('gnanesh',7084,98.01)]Â
# iterate using for loopfor x in name:     # iterate in each tuple element  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
Method 2: Using enumerate()
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
# create a list of tuples with student# detailsname = [('sravan',7058,98.45),        ('ojaswi',7059,90.67),        ('bobby',7060,78.90),        ('rohith',7081,67.89),        ('gnanesh',7084,98.01)]l = []Â
# iterate using index with enumerate functionfor index, tuple in enumerate(name):           # access through index      # by appending to list    l.append(name[index])     # iterate through the listfor 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

… [Trackback]
[…] Find More on to that Topic: geeksforgeeks.org/how-we-can-iterate-through-list-of-tuples-in-python/ […]
… [Trackback]
[…] Find More here to that Topic: geeksforgeeks.org/how-we-can-iterate-through-list-of-tuples-in-python/ […]
… [Trackback]
[…] There you can find 57646 additional Info to that Topic: geeksforgeeks.org/how-we-can-iterate-through-list-of-tuples-in-python/ […]