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.
# 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)) |
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.
# 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)) |
The original list : [[1, 'Geeks'], [2, 'For'], [3, 'Geeks']] Index of nested element is : 1
Recommended Posts:
- Python | Get last element of each sublist
- Python | Get first element of each sublist
- Python | Maximum Sum Sublist
- Python | Replace sublist with other in list
- Python | Shift sublist in list
- Python | Find maximum value in each sublist
- Python | Getting sublist element till N
- Python | Split Sublist Strings
- Python | Add the element in the list with help of indexing
- Python | Remove sublists that are present in another sublist
- Python | Multiply each element in a sublist by its index
- Python | Sort a list according to the second element in sublist
- Python | Find the sublist with maximum value in given nested list
- Basic Slicing and Advanced Indexing in NumPy Python
- Boolean Indexing in Pandas
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.



