Python – Create list of tuples using for loop
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) |
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) |
List of Tuples [(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
Method 3: Using zip() function
Using Python’s zip() function we can create a list of tuples, for that we will require two lists.
Step-by-step approach:
- Firstly, initialize two variables that will hold some values as a list and the other one will hold the indexes of those values as a list.
- Then use another variable in which we will hold the result of our zip() Operation. Then we need to convert the result of the zip function into a list.
- We will then print the variable.
Below is the implementation of the above approach:
Python3
# Defining arr1 arr1 = [ 5 , 4 , 2 , 5 , 6 , 1 ] # Creating the second array which # holds the index values of previous array arr2 = [i for i in range ( len (arr1))] # converting the result into list res = list ( zip (arr1,arr2)) # printing the result print (res) |
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
Time Complexity – O(min(len(iterable_1), len(iterable_2)))
Auxiliary Space – O(n)