Access an element in a 2D list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Access an element in a 2D list in Python #

Use square brackets to access an element in a 2D list, e.g. my_2d_list[0][0]. The first set of square brackets represents the index of the nested list and the second set represents the index of the element in the specified nested list.

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

We used square bracket notation to access an element in a two-dimensional list.

The first set of square brackets represents the index of the nested list.

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

The second set of square brackets represents the index of the item in the nested list.

main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] print(my_2d_list[0][1]) # 👉️ 'two' print(my_2d_list[1][1]) # 👉️ 'four'
Python indexes are zero-based. The first item in a list has an index of 0, and the last an index of -1 or len(my_list) - 1.

You can use the same syntax if you need to update the value of an item in a two-dimensional list.

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

If you try to access an index that is not present in the list, you'd get an IndexError.

main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] # ⛔️ IndexError: list index out of range print(my_2d_list[3][0])

The two-dimensional list only contains 3 items, so the last item in the list has an index of 2.

You can use a try/except statement to handle the scenario where the index is out of range.

main.py
my_2d_list = [['one', 'two'], ['three', 'four'], ['five', 'six']] try: print(my_2d_list[3][0]) except IndexError: # 👇️ this runs print('provided index out of range')

An IndexError is raised and is then handled by the except block.

You can use the list.index() method if you need to find the index of an item in a two-dimensional list.

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

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

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

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.