Find index of element in a Two-dimensional list in Python

avatar

Borislav Hadzhiev

Last updated: Jul 7, 2022

banner

Photo from Unsplash

Find index of element in a Two-dimensional list in Python #

To find the index of an element in a two-dimensional list:

  1. Use a generator expression to iterate over the list.
  2. Check if the specified value is contained in each nested list.
  3. Use the list.index() method to get the index of the nested list and the index of the value.
main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] if any('two' in (match := nested_list) for nested_list in my_2d_list): # 👇️ this runs print('Two is contained in the two-dimensional list') list_index = my_2d_list.index(match) print(list_index) # 👉️ 0 value_index = match.index('two') print(value_index) # 👉️ 1 print(my_2d_list[list_index][value_index]) # 👉️ 'two' else: print('Two is NOT contained in the two-dimensional list')

We used a generator expression to iterate over the two-dimensional list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if a value is contained in the current nested list.

We used the assignment expression syntax to assign the matching nested list to a variable.

main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] if any('two' in (match := nested_list) for nested_list in my_2d_list): list_index = my_2d_list.index(match) print(list_index) # 👉️ 0 value_index = match.index('two') print(value_index) # 👉️ 1 print(my_2d_list[list_index][value_index]) # 👉️ 'two'

Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.

The list.index() method returns the index of the first item whose value is equal to the provided argument.

main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] print(my_2d_list.index(['one', 'two'])) # 👉️ 0 print(my_2d_list[0].index('two')) # 👉️ 1

The method raises a ValueError if there is no such item in the list.

However, the method won't raise a ValueError in our scenario because the if block runs only if the value is contained in a nested list.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.