Get Started

Subset a nested list

You can also extract an element from the list you extracted. To do this, you use two indices. The first index is the position of the list, and the second index is the position of the element within the list.

For example, if you want to extract 7 from x, you can use the following command:

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

7

Here the first index 2 refers to the third list in x and the second index 0 refers to the first element of the third list in x.

The nested list stocks you created in the last exercise is available in your workspace and is printed in the IPython shell on the right.

This is a part of the course

“Introduction to Python for Finance”

View Course

Exercise instructions

  • From the nested list stocks, subset 'Coca-Cola'.
  • From the nested list stocks, subset the price for Walmart stock, i.e., 71.17.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Use indexing to obtain company name Coca-Cola
print(stocks[____][____])

# Use indexing to obtain 71.17
print(stocks[____][____])
Edit and Run Code