2D Lists Indexing

Remember: - Lists can be used to group different values together - it’s just a collection of things. - You can make a list in Python by putting different things in a box of brackets [] separated by commas - You can make lists of lists, which are called 2D lists

Here we’re going to learn how to index lists of lists. Let’s recreate our 2D list of food:

# create 2D list
food = [['apple', 'banana', 'grape', 'mango'], 
        ['lettuce','carrot','cucumber','beet'], 
        ['chicken', 'beef', 'fish', 'pork']]

# print 2D list along with its length
print(food)
print(len(food))
[['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet'], ['chicken', 'beef', 'fish', 'pork']]
3

Like we saw in the last lesson, the length of the food list (3) is the number of 1D lists that make up the 2D list. The fruit list is the first element in food. To get this first element from food, we do it the same way we would in a 1D list:

# get the fruit list from the food list
food[0]
['apple', 'banana', 'grape', 'mango']

In this way, we can think of the list food as a 1D list, where each element is another list. As we saw in the last command, we can reference the first sublist from food using food[0].

Knowing this, how can we get the length of the first list within food?

# print length of the first index of food
len(food[0])
4

Thinking back to indexing 1D lists, how do you think we can get the lists fruit and vegetables from the list food?

# get fruit and vegetables from the list
food[0:2]
[['apple', 'banana', 'grape', 'mango'],
 ['lettuce', 'carrot', 'cucumber', 'beet']]

What if we want to get the value 'mango' from our list? We can first save the first element from food to a variable fruit, and then index the fruit list:

# get the fruit list from food and save it in the variable fruit
fruit = food[0]

# print the fruit list to make sure you got what you wanted
print(fruit)

# get mango from the fruit list
fruit[3]
['apple', 'banana', 'grape', 'mango']
'mango'

We can also get the value 'mango' from our list in one line! To do this, we can just index food twice. The first index is to get the fruit list, and the second index is to get 'mango' from the fruit list:

# get mango by indexing the food list twice
food[0][3]
'mango'

How can you get 'carrot' from the food 2D list?

# get carrot from the food 2D list
food[1][1]
'carrot'

Now, try getting 'fish' and 'pork' from the food 2D list:

# get fish and pork from the food 2D list
food[2][2:4]
['fish', 'pork']

Finally, let’s make a new list called favorites with your favorite food within each list in food. Print it out afterwards to make sure you did what you want!

# make a list of your favorite fruit, vegetable, and meat
favorites = [food[0][3], food[0][2], food[2][1]]

# print favorite
print(favorites)
['mango', 'grape', 'beef']

Nice job! You just learned how to index 2D lists in Python!