How to use zip() function In Python
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) |
Output
[(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)
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.
Contact Us