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[____][____])

This exercise is part of the course

Introduction to Python for Finance

BeginnerSkill Level
4.7+
29 reviews

Build Python skills to elevate your finance career. Learn how to work with lists, arrays and data visualizations to master financial analyses.

This chapter introduces lists in Python and how they can be used to work with data.

Exercise 1: ListsExercise 2: Creating lists in PythonExercise 3: Indexing list itemsExercise 4: Slicing multiple list elementsExercise 5: Nested listsExercise 6: Stock up a nested listExercise 7: Subset a nested list
Exercise 8: List methods and functionsExercise 9: Exploring list methods and functionsExercise 10: Using list methods to add dataExercise 11: Finding stock with maximum price

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free