Skip to content
Related Articles

Related Articles

Improve Article

Python – Create list of tuples using for loop

  • Last Updated : 14 Sep, 2021

In this article, we will discuss how to create a List of Tuples using for loop in Python.

Let’s suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index.

Method 1: Using For loop with append() method

Here we will use the for loop along with the append() method. We will iterate through elements of the list and will add a tuple to the resulting list using the append() method.

Example:

Python3




L = [5, 4, 2, 5, 6, 1]
res = []
  
for i in range(len(L)):
    res.append((L[i], i))
      
print("List of Tuples")
print(res)


Output



List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]

Method 2: Using For loop with enumerate() method

Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. So we can use this function to create the desired list of tuples.

Example:

Python3




L = [5, 4, 2, 5, 6, 1]
res = []
  
for index, element in enumerate(L):
    res.append((element, index))
      
print("List of Tuples")
print(res)


Output

List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]

 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 :