Python Indexing a sublist

PythonServer Side ProgrammingProgramming

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.

Input

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

Output

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

Example

 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
      break
   # breaking the outer loop
   if is_found:
      break
   # 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")
index(7)
index(5)
index(3)

Output

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

Conclusion

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

raja
Published on 07-Jul-2020 12:20:21
Advertisements