Python Lists
meals keeps three values in the order you write them: rice, then soup, then bread. They sit inside square brackets, with a comma between values. The places are numbered from 0, so the first value is not in place 1. You read a place by writing the name, then the place number in brackets.
meals[0] is rice. meals[1] is soup. meals[2] is bread. The number inside the brackets is the place. There is no place 3 in this list.
meals = ["rice", "soup", "bread"]
print(meals[0])
print(meals[2])
The screen shows rice, then bread. Those lines follow the places you asked for, not every value in order. soup is still in the list, at place 1. This program simply does not print that place.
A list can hold numbers. counts keeps 2, then 0, then 5. counts[0] is 2. counts[1] is 0. That 0 is the number stored in the second place. It is not the number of the first place. 5 sits at place 2, and this program does not print it.
counts = [2, 0, 5]
print(counts[0])
print(counts[1])
The screen shows 2, then 0. The 0 was written into the list. It is the value at place 1.
len(meals) is 3, because meals has three values. The last place is 2, one less than the length, and that place is bread. meals[3] is past the end. The program stops there. That line is not in the programs above.
Two easy misreadings
The first value is place 0, not place 1. If you print meals[1] expecting rice, you get soup. In counts, the 0 on the screen is a stored number. The first place in that list is still 0, and the value there is 2.
The next page adds a value and takes one away. This page only reads a place that is already in the list.
Read the places
- What does the first program write, first and then?
- What is meals[1]?
- What does the second program write, first and then?
- You write meals[3]. Does the program finish?
- What is len(meals)?
The places in the list
meals keeps rice, soup, and bread in that order. Place 0 is rice, place 1 is soup, and place 2 is bread, so the first program writes rice, then bread. counts[1] is the stored number 0, and the second program writes 2, then 0. len(meals) is 3. meals[3] stops the program.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top