Python Indexing a sublist

In this tutorial, we are going to write a program that finds the index of a sublist element from the list. Let's see an example to understand it clearly.


nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]


Index of 7:- 2
Index of 5:- 1
Index of 3:- 0

Let's see the simple and most common way to solve the given problem. Follow the given steps solve it.

  • Initialize the list.
  • Iterate over the list using the index.
  • Iterate over the sub list and check the element that you want to find the index.
  • If we find the element then print and break it


 Live Demo

# initializing the lit
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# function to find the index
def index(element):
# initializing a flag for tracking the element
is_found = False
# iterating over the list
for i in range(len(nested_list)):
   # iterating over the sub list
   for j in range(len(nested_list[i])):
      # cheking for the element
      if nested_list[i][j] == element:
         # printing the sub list index that contains the element
         print(f'Index of {element}: {i}')
         # changing the flag to True
         is_found = True
      # breaking the inner loop
   # breaking the outer loop
   if is_found:
   # checking whether the element is found or not
   if not is_found:
      # printing the element not found message
      print("Element is not present in the list")


If you run the above code, then you will get the following result.

Index of 7: 2
Index of 5: 1
Index of 3: 0


If you have any queries regarding the tutorial, mention them in the comment section

Updated on: 07-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started