![]() |
VOOZH | about |
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.
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:
List of Tuples [(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
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:
List of Tuples [(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]
Using Python's zip() function we can create a list of tuples, for that we will require two lists.
Step-by-step approach:
Below is the implementation of the above approach:
[(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)