Skip to content
Related Articles

Related Articles

Improve Article

How we can iterate through list of tuples in Python

  • Last Updated : 23 Aug, 2021
Geek Week

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 
# details
name = [('sravan',7058,98.45),
        ('ojaswi',7059,90.67),
        ('bobby',7060,78.90),
        ('rohith',7081,67.89),
        ('gnanesh',7084,98.01)]
  
# iterate using for loop
for 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 with atudent
# details
name = [('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 emumerate function
for index, tuple in enumerate(name):
        
    # access through index
      # by appending to list
    l.append(name[index])
      
# iterate through the list
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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :