Lists
Lists are generic containers that can store heterogeneous data in Python. In this example, you'll store data about a person in a list. The list will contain the following data (in that order):
- First name
- Last name
- Sex
- Employment status
- Number of twitter followers
Recall that you can use square brackets to extract values out of a list.
Since Python is a 0-indexed language, the first element has an index of 0.
If you want to extract multiple consecutive values, you can use the colon (:
).
Python is a left-inclusive, right-exclusive language, meaning when specifying a range,
the starting value will be included, but the ending value will not be included. So to extract the first four values of the list x, you can use:
x = [1, 2, 3, 4, 5]
print(x[0:4])
[1, 2, 3, 4]
You can also specify negative indices to subset elements. When you do this, remember to start counting from the end of the list. To extract the last element from a list, you can use:
print(x[-1])
5
This exercise is part of the course
Python for R Users
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Assign the values to the list
____ = ____