Subset and conquer
Subsetting Python lists is a piece of cake. Take the code sample below, which creates a list x
and then selects "b" from it. Remember that this is the second element, so it has index 1. You can also use negative indexing.
x = ["a", "b", "c", "d"]
x[1]
x[-3] # same result!
Remember the areas
list from before, containing both strings and floats? Its definition is already in the script. Can you add the correct code to do some Python subsetting?
This is a part of the course
“Introduction to Python”
Exercise instructions
- Print out the second element from the
areas
list (it has the value11.25
). - Subset and print out the last element of
areas
, being9.50
. Using a negative index makes sense here! - Select the number representing the area of the living room (
20.0
) and print it out.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Print out second element from areas
print(areas[____])
# Print out last element from areas
print(areas[____])
# Print out the area of the living room
print(areas[____])
This exercise is part of the course
Introduction to Python
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
Learn to store, access, and manipulate data in lists: the first step toward efficiently working with huge amounts of data.
Exercise 1: Python ListsExercise 2: Create a listExercise 3: Create lists with different typesExercise 4: List of listsExercise 5: Subsetting ListsExercise 6: Subset and conquerExercise 7: Slicing and dicingExercise 8: Subsetting lists of listsExercise 9: Manipulating ListsExercise 10: Replace list elementsExercise 11: Extend a listExercise 12: Delete list elementsExercise 13: Inner workings of listsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.