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.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Use a list as a queue of work
Lists are useful when a program must keep several related values in a chosen order. A short queue of lessons can gain an item at the end with append. The pop method can remove and return an item at a particular index. Removing index 0 means taking the first queued item, after which later items shift left.
Follow this queue through each change rather than memorizing a snapshot. The original list has two lessons, then a third is appended, then the first is removed. Predict the remaining list before running the code. Try changing pop(0) to pop() and notice that the default removes the last item instead.
queue = ["intro", "lists"]
queue.append("loops")
next_up = queue.pop(0)
print(next_up)
print(queue)intro
['lists', 'loops']- append places 'loops' after the existing items.
- pop(0) returns and removes the first item.
- The remaining list keeps its relative order.
A slice describes a range, not one index
An index selects one item; a slice selects a range. In items[start:stop], the start is included and the stop is excluded. This lets you use a count as the stop: items[:2] gets the first two items. A slice creates a new list, so it can be an easy snapshot of part of a larger collection.
Notice that asking for a slice past the end simply returns the available items, whereas direct indexing past the end raises IndexError. That difference makes slices practical for preview cards or a small first page of results. Predict whether topics[1:3] includes the item at index 3 before you run it.
topics = ["history", "print", "lists", "loops"]
print(topics[1:3])
print(topics[:10])['print', 'lists']
['history', 'print', 'lists', 'loops']- The first slice includes indexes 1 and 2, stopping before 3.
- The second slice starts at the beginning and safely stops at the list end.
- Both expressions produce new list values.
Shared names versus an independent copy
Two names can point to the same mutable list. Assigning alias = original does not copy its contents: changing the list through either name affects the single shared object. When you need a separate list that can diverge, call copy() or take a full slice. This matters when preserving an original plan while experimenting with a revised one.
In the example, the alias adds a topic to the original list. The copy is made afterward, so it starts with all three topics. Adding another item to the copy leaves the original alone. Before running the code, predict which list will contain 'files'. Then move the copy() call above the first append and reconsider the result.
original = ["intro", "lists"]
alias = original
alias.append("loops")
revised = original.copy()
revised.append("files")
print(original)
print(revised)['intro', 'lists', 'loops']
['intro', 'lists', 'loops', 'files']- alias and original refer to one list, so the first append is shared.
- copy() creates a second outer list with the current contents.
- Appending to revised changes only that second list.
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.