Finding an element in a list of lists can be a little tricky in Python. This tutorial will show you how to do it step-by-step.
Step 1: Create a list of lists
Create a list of lists by enclosing your lists in square brackets. Here’s an example:
my_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
Step 2: Use a for loop to search for the element
In order to search for an element in a list of lists, we need to use a nested for loop. The outer for loop will iterate through each list in the list of lists, and the inner for loop will iterate through each element in each list. Here’s an example:
1 2 3 4 5 6 |
element_to_find = 5 for my_list in my_list_of_lists: for element in my_list: if element == element_to_find: print("Element found!") |
This code will output “Element found!” because 5 is in the second list.
Step 3: Return the index of the element
If you want to know the specific index of the element, you can modify the code from Step 2. Here’s an example:
1 2 3 4 5 6 |
element_to_find = 5 for i, my_list in enumerate(my_list_of_lists): if element_to_find in my_list: j = my_list.index(element_to_find) print("Element found at index ({},{})!".format(i,j)) |
This code will output “Element found at index (1,1)!” because 5 is at index 1 in the second list.
Here’s the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
my_list_of_lists = [[1,2,3], [4,5,6], [7,8,9]] element_to_find = 5 # Step 2 - Find the element for my_list in my_list_of_lists: for element in my_list: if element == element_to_find: print("Element found!") # Step 3 - Return the index of the element for i, my_list in enumerate(my_list_of_lists): if element_to_find in my_list: j = my_list.index(element_to_find) print("Element found at index ({},{})!".format(i,j)) |
Output:
Element found! Element found at index (1,1)!
Conclusion:
Finding an element in a list of lists in Python is a little more complicated than finding an element in a simple list. By using a nested for loop and the index method, you can easily find the element you’re looking for.