Tutorials
python

Python List Function

Learn how you can subset a nested list in Python.

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.

Exercise

TRY IT YOURSELF: Access the exercise in our Introduction to Python for Finance course here.

  • From the nested list stocks, subset 'Coca-Cola'.
  • From the nested list stocks, subset the price for Walmart stock, i.e., 71.17.
# Use indexing to obtain company name Coca-Cola
print(stocks[____][____])

# Use indexing to obtain 71.17
print(stocks[____][____])

Video

To learn more about list methods and functions, please see this video from our course Introduction to Python for Finance.

This content is taken from DataCamp’s Introduction to Python for Finance course by Adina Howe.