Python | Convert list to indexed list of tuples

Python Methods and Functions

Method # 1: Using list () + enumerate ()
A combination of the above functions can be used to accomplish this particular task. In this case, we simply pass an enumerated list to list (), which returns a tuple with the first element as the index and the second as the list element for that index.

# Python3 code to demonstrate how it works
# Convert list to indexed tuple
# Using list () + enumerate ()

 
# initializing list

test_list = [ 4 , 5 , 8 , 9 , 10 ]

 
# print list

print ( "The original list:" + str (test_list))

 
# Convert list to indexed tuple
# Using list () + enumerate ()

res = list ( enumerate (test_list))

 
# Print result

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 # 2: Using zip () + range ()
A combination of the above functions can also be used to accomplish this particular task. In this we just use the ability of zip () to convert to a tuple and range () to get the index of the element to length. This pair indexes the value in the form of a list of tuples.

# Python3 code to demonstrate how it works
# Convert list to indexed tuple
# Using zip () + range ()

 
# initializing list

test_list = [ 4 , 5 , 8 , 9 , 10 ]

 
# print list

print ( "The original list:" + str (test_list))

 
# Convert list to indexed tuple
# Using zip () + range ()

res = list ( zip ( range ( len (test_list)), test_list))

 
# Print result

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)] 




Get Solution for free from DataCamp guru