Python | Convert list to indexed tuple list
Last Updated :
12 Apr, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to convert a list to tuple. This kind of problem have been dealt with before. But sometimes, we have it’s variation in which we need to assign the index of the element along with element as a tuple. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + enumerate()
Combination of above functions can be used to perform this particular task. In this, we just pass the enumerated list to list(), which returns the tuple with first element as index and second as list element at that index.
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
res = list ( enumerate (test_list))
print ( "List after conversion to tuple list : " + str (res))
|
Output :
The original list : [4, 5, 8, 9, 10]
List after conversion to tuple list : [(0, 4), (1, 5), (2, 8), (3, 9), (4, 10)]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. list() + enumerate() performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2: Using zip() + range()
The combination of above functions can also be used to perform this particular task. In this, we just use the ability of zip() to convert to tuple and range() to get element index till length. This pairs index to value in form of tuple list.
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
res = list ( zip ( range ( len (test_list)), test_list))
print ( "List after conversion to tuple list : " + str (res))
|
Output :
The original list : [4, 5, 8, 9, 10]
List after conversion to tuple list : [(0, 4), (1, 5), (2, 8), (3, 9), (4, 10)]
Method #3 : Using lists and append() method
Python3
test_list = [ 4 , 5 , 8 , 9 , 10 ]
print ( "The original list : " + str (test_list))
res = []
for i in range ( 0 , len (test_list)):
res.append((i,test_list[i]))
print ( "List after conversion to tuple list : " + str (res))
|
Output
The original list : [4, 5, 8, 9, 10]
List after conversion to tuple list : [(0, 4), (1, 5), (2, 8), (3, 9), (4, 10)]
Share your thoughts in the comments
Please Login to comment...