Sunday, December 29, 2024
Google search engine
HomeLanguagesHow we can iterate through list of tuples in Python

How we can iterate through list of tuples in Python

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 student
# 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 enumerate 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

RELATED ARTICLES

Most Popular

Recent Comments