Lists
Create a list, access its items, and change its contents.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A list keeps values in an ordered collection. Index 0 is the first item, and index -1 is the last item. Square brackets select an item or a slice.
Lists can change after creation. Use append() to add an item, or assign to an existing index to replace one. The len() function reports how many items a list contains.
- Indexes begin at 0
- Lists are mutable
- append() adds one item
See it step by step
Read the code, predict the output, then compare it with the result.
01. Append a topic
topics = ["strings", "loops"]
topics.append("dictionaries")
print(topics)['strings', 'loops', 'dictionaries']append() puts one new value at the end of the existing list.
02. Replace and inspect
colors = ["red", "blue", "green"]
colors[0] = "yellow"
print(colors[-1])
print(len(colors))green
3Index 0 changes the first item; index -1 reads the last item. The list still has three items.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Use topics.append('dictionaries') to grow the list. Replace the item at index 0 with 'variables', then print(topics[-1]).
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Index past the end
items = ["a", "b"]
print(items[2])items = ["a", "b"]
print(items[1])What happens: IndexError because the only valid positive indexes are 0 and 1.
The final positive index is len(items) - 1.
Saving append's return value
items = [1, 2]
items = items.append(3)
print(items)items = [1, 2]
items.append(3)
print(items)What happens: The variable becomes None.
Call append without assigning its return value.