Collections
Lists and indexing
Create an ordered list, access its elements, and change or append values.
Lesson 18 of 63
Reading: about 2 min
Lesson + practice: about 12 min
Difficulty: Beginner
On this page4 sections
A list stores values in order. Indexes start at 0, so the first item is at index 0. Negative indexes count back from the end. Lists are mutable: you can replace or append items.
minutes = [20, 25, 30]
print(minutes[0])
print(minutes[-1])
minutes[1] = 35
minutes.append(40)
print(minutes)20 30 [20, 35, 30, 40]
Use a list in a loop
A for loop can visit each value directly. len() reports how many items the list contains.
minutes = [20, 25, 30]
for value in minutes:
print(value)
print(len(minutes))20 25 30 3
Why this works
A list keeps an ordered sequence, so its position has meaning. The first item uses index 0, the second index 1, and index -1 accesses the last item. Assigning to an existing index replaces one value; append() adds a new value at the end.
Practice
Create a list of three study subjects. Print the first and last items, replace the middle item, then append a fourth subject.
What is the index of the first item in a Python list?
Reveal answer
Index 0.
Try another case
After values = [5, 10] and values.append(15), what are values[1] and values[-1]?
Check your answer
Reveal answer
values[1] is 10 and values[-1] is 15.
Your progress
Reveal the check answer or reach the end to complete this lesson.