Python | Indexing a sublist

In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let’s discuss certain ways in which this can be performed.

Method #1 : Using index() + list comprehension
This method solves this problem in 2 parts, for the first part it generates a new list and then it performs indexing on it.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# indexing of sublist 
# using list comprehension + index()
  
# initializing test list
test_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using list comprehension + index()
# indexing of sublist
res = [ele for i, ele in test_list].index('For')
  
# print result
print("Index of nested element is : " + str(res))

chevron_right


Output :



The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
Index of nested element is : 1

 

Method #2 : Using next() + enumerate()
This problem can be solved in an efficient manner using the combination of the above functions. The next function checks for the elements and enumerate functions separates the nested list elements.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# indexing of sublist 
# using enumerate() + next()
  
# initializing test list
test_list = [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using enumerate() + next()
# indexing of sublist
res = next((i for i, (j, ele) in enumerate(test_list) if ele == 'For'), None)
  
# print result
print("Index of nested element is : " + str(res))

chevron_right


Output :

The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']]
Index of nested element is : 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.