Python lists
A list is like a row of school lockers. Every locker holds one thing, and every locker has its own number. Click a locker to open it!
What is a list?
A list stores many values in one place. In Python, we write a list with square brackets [ ].
Imagine you want to save the names of four students. You could make four variables. That is a lot of typing! A list is much shorter.
Without a list
student1 = "Ana" student2 = "Budi" student3 = "Citra" student4 = "Dewi"
With a list
students = ["Ana", "Budi", "Citra", "Dewi"]
One name. Four students. Easy to add more!
Four things to know about lists
- Ordered. Items stay in the order you put them. The first item stays first.
- Changeable. You can change, add and remove items after you make the list. Python calls this mutable.
- Any type. A list can hold text, numbers, True/False, and even other lists. You can mix them.
- Duplicates are OK. The same value can appear many times:
[1, 1, 2]is fine.
Lists in real life
You already use lists every day. Programmers use Python lists to build things like these:
- A music playlist. Songs in order. You can add, remove and skip songs.
- The contacts on your phone. A long list of names.
- A game backpack. Sword, shield, potion. Pick up items, use items.
- A to-do list. Add a task. Tick it off. Remove it.
- Class test scores. Find the best score and the average.
1Create a list
To make a list, put your items inside square brackets. Put a comma between the items.
- fruits is the name of the list. Python calls it a variable.
- = puts the list into the name.
- [ ] square brackets hold all the items.
- "apple" is one item. Text needs quotes.
- , commas go between the items.
Rules for writing items
- Text needs quotes:
"apple"or'apple'. - Numbers do not need quotes:
90,3.5. - True and False start with a capital letter and have no quotes.
- Choose a clear name, like
fruitsorscores. No spaces. Use_if you need two words, likemy_list.
Kinds of lists
A list can hold many kinds of values. Pick a tab, press Run, then try to change the code!
A list of words. Each word is a string, so it needs quotes.
fruits = ["apple", "banana", "cherry"] print(fruits)
Numbers have no quotes. Whole numbers are int. Numbers with a point are float.
scores = [90, 85, 77] prices = [1.5, 2.25, 3.0] print(scores) print(prices)
True and False are called booleans. Notice the capital letters.
answers = [True, False, True] print(answers)
You can mix types in one list. This list describes one student.
student = ["Rina", 13, 1.55, True] print(student) print(type(student))
An empty list has no items yet. It is great for starting a to-do list or a game score list.
todo = [] print(todo) print(len(todo))
A list can hold other lists. This is useful for tables, like names with scores.
class_a = [["Ana", 90], ["Budi", 85]] print(class_a)
More ways to make a list
letters = list("hey") # split text into letters
print(letters)
numbers = list(range(1, 6)) # 1 to 5 (stops BEFORE 6)
print(numbers)
zeros = [0] * 5 # repeat an item 5 times
print(zeros)
both = ["a", "b"] + ["c", "d"] # join two lists
print(both)
Tip: Do not name your list list. That is the name of a built-in Python tool. Use a clear name like fruits instead.
2Access items
To open a locker, write the list name and then the locker number inside [ ]. This number is called the index.
Very important: Python starts counting at 0, not 1. The first item is index 0. The second item is index 1. And so on.
fruits = ["apple", "banana", "cherry", "mango", "grape"] print(fruits[0]) # the first item print(fruits[2]) # the third item print(fruits[4]) # the fifth (last) item
Why 0? Think of the index as "how many steps from the start". The first item is 0 steps away.
Negative index: count from the end
A negative number counts from the right side. -1 is the last item, -2 is the second from last. The small numbers under each locker are the negative indexes.
fruits = ["apple", "banana", "cherry", "mango", "grape"] print(fruits[-1]) print(fruits[-2])
How many items? Use len()
len() tells you how many items are in a list. The last index is always len() - 1.
fruits = ["apple", "banana", "cherry", "mango", "grape"] print(len(fruits)) last_index = len(fruits) - 1 print(last_index) print(fruits[last_index])
Slicing: get a few items
A slice takes a piece of the list. Write [start:stop]. Python starts at start and stops just before stop. The stop locker is not included!
fruits = ["apple", "banana", "cherry", "mango", "grape"] print(fruits[1:3]) # index 1 and 2 (stops BEFORE 3) print(fruits[:2]) # from the start print(fruits[2:]) # to the end print(fruits[-2:]) # the last two
A list inside a list
Use two indexes to go inside. The first opens the big locker. The second opens a small locker inside it.
classroom = [["Ana", "Budi"], ["Citra", "Dewi"]] print(classroom[0]) print(classroom[1][0])
What if the locker does not exist?
If you use an index that is too big, Python shows an IndexError. Press Run to see it. Then change pets[3] to pets[2].
pets = ["cat", "dog", "fish"] print(pets[0]) print(pets[3])
Sneak peek: Later you will learn to open every locker with a loop. It looks like this:
for pet in pets:
print(pet)
3Update data
Lists are mutable. That means you can change them after you make them. You can put new things in the lockers, add new lockers, or remove lockers.
Change an item
Use the index and =. The old item is replaced by the new one.
colors = ["red", "green", "blue"] colors[1] = "yellow" print(colors)
Add items
append(x)addsxat the end.insert(i, x)putsxat indexi. The other items move to the right.extend(list)adds many items at the end.
snacks = ["chips", "cookies"]
snacks.append("candy")
print(snacks)
snacks.insert(1, "popcorn")
print(snacks)
snacks.extend(["nuts", "raisins"])
print(snacks)
Remove items
remove(x)removes the first item that has the valuex.pop()removes the last item and gives it back.pop(i)removes the item at indexi.del list[i]deletes the item at indexi.
pets = ["cat", "dog", "fish", "bird", "hamster"]
pets.remove("fish") # remove by VALUE
print(pets)
last = pets.pop() # remove the LAST item and keep it
print(last)
print(pets)
del pets[0] # remove by INDEX
print(pets)
Put the list in order
numbers = [30, 10, 20] numbers.sort() # small to big print(numbers) numbers.reverse() # flip the order print(numbers) names = ["Zara", "Ali", "Mia"] names.sort() # A to Z print(names) names.sort(reverse=True) # Z to A print(names)
Which tool should I use?
| Tool | What it does | Example |
|---|---|---|
list[i] = x | Replaces the item at index i | colors[1] = "pink" |
append(x) | Adds one item at the end | snacks.append("candy") |
insert(i, x) | Adds one item at index i | snacks.insert(0, "nuts") |
extend(list) | Adds many items at the end | snacks.extend(["a", "b"]) |
remove(x) | Removes the first item equal to x | pets.remove("cat") |
pop(i) | Removes item at index i and gives it back | pets.pop(0) |
del list[i] | Deletes item at index i | del pets[0] |
sort() / reverse() | Changes the order | scores.sort() |
Remember: sort(), append(), insert() and remove() change the list itself. They do not make a new list.
Real-life cases
Let us use what you learned to solve real problems. Press Run, then change the code to see what happens.
Case 1: Your music playlist
You love music. You want to make a playlist, add new songs, change one, and delete one you do not like. A list does all of this!
playlist = ["Sunrise", "Ocean Eyes", "Skyline"]
print("Songs:", playlist)
playlist.append("Dream Big") # add a song at the end
playlist.insert(0, "Intro Beat") # put a song first
playlist[2] = "Ocean Eyes (Remix)" # change a song
playlist.remove("Skyline") # delete a song
print("Now playing:", playlist[0])
print("Last song:", playlist[-1])
print("Total songs:", len(playlist))
print(playlist)
You used: create, index 0, index -1, len(), append, insert, change by index, remove.
Your turn: Add your own favourite song to the end of the playlist.
Case 2: Order at the school canteen
You order food for your group. Your friends add more food. Then you change your mind about a drink.
order = ["fried rice", "iced tea"]
order.append("meatball soup")
order.extend(["tempeh", "orange juice"])
print("My order:", order)
print("Items:", len(order))
# I changed my mind!
order[1] = "mineral water"
order.remove("tempeh")
print("Final order:", order)
You used: extend() to add many items at once, and change by index.
Your turn: Use pop() to take away the last item. What does it give back?
Case 3: Class test scores
A teacher saves test scores in a list. She finds the best and lowest score, and the average. One student takes a remedial test, so one score changes.
scores = [78, 85, 92, 66, 88]
print("Scores:", scores)
print("Best score:", max(scores))
print("Lowest score:", min(scores))
print("Average:", sum(scores) / len(scores))
# Remedial test! Update the lowest score
scores[3] = 80
print("New average:", sum(scores) / len(scores))
scores.sort()
print("From low to high:", scores)
You used: max(), min(), sum(), len(), update by index, sort().
Your turn: Add your own score with append(). How does the average change?
Case 4: Backpack in a video game
In a game, your backpack has slots. Each slot has a number. You pick up things, use them and upgrade them.
bag = ["sword", "shield", "potion"]
print("Slot 0 has:", bag[0])
bag.append("map") # pick up a map
bag.insert(1, "bow") # put a bow in slot 1
print("Bag:", bag)
used = bag.pop() # use the last item
print("Used:", used)
bag[0] = "super sword" # upgrade!
print("Bag now:", bag)
print("Is there a potion?", "potion" in bag)
You used: pop() to use and remove an item, and in to check if something is inside.
Your turn: Change the shield into a "magic shield".
Oops! Common mistakes
Everyone makes these mistakes. Open each one, run the code, and read the message. Error messages are your friends!
Mistake 1: Counting from 1
fruits = ["apple", "banana", "cherry"] print(fruits[3])
fruits[2] or fruits[-1].Mistake 2: Forgetting the quotes
names = [Ana, Budi] print(names)
names = ["Ana", "Budi"].Mistake 3: Round brackets instead of square brackets
fruits = ["apple", "banana"] print(fruits(0))
fruits[0].Mistake 4: Removing something that is not there
fruits = ["apple", "banana"]
fruits.remove("mango")
"mango" in fruits. Also check the spelling and capital letters.Mistake 5: append() when you wanted extend()
x = [1, 2, 3] x.append([4, 5]) print(x) print(len(x)) y = [1, 2, 3] y.extend([4, 5]) print(y) print(len(y))
append() adds one item. Here the item is a whole list, so it goes inside one locker. Use extend() to add many items.Mistake 6: Saving the result of sort()
scores = [30, 10, 20] scores = scores.sort() print(scores)
sort() changes the list and gives back None. Just write scores.sort(). Or use sorted(scores) to get a new sorted list.Mistake 7: Trying to change a letter in text
name = "Ana" name[0] = "E"
name = "Eva".Mistake 8: Two names, one list
a = ["x", "y"]
b = a # NOT a copy!
b.append("z")
print(a)
c = a.copy() # this IS a copy
c.append("w")
print(a)
print(c)
b = a gives the same list a second name. Use a.copy() when you need a separate copy.Playground
Write your own Python code here. Every list you make will appear as lockers below.
Missions
Six coding missions. Write the code, then press Run & check. Stuck? Use the hint!
Quick quiz
Eleven questions. You get feedback after each answer.
Cheat sheet
Here fruits = ["apple", "banana", "cherry"].
| I want to... | Code | Result |
|---|---|---|
| Make a list | fruits = ["apple", "banana"] | A list with 2 items |
| Make an empty list | todo = [] | No items yet |
| Get the first item | fruits[0] | 'apple' |
| Get the last item | fruits[-1] | 'cherry' |
| Count the items | len(fruits) | 3 |
| Get a slice | fruits[0:2] | ['apple', 'banana'] |
| Change an item | fruits[0] = "kiwi" | Index 0 is now kiwi |
| Add at the end | fruits.append("mango") | mango is last |
| Add at a place | fruits.insert(1, "pear") | pear is at index 1 |
| Add many items | fruits.extend(["a", "b"]) | a and b are at the end |
| Remove by value | fruits.remove("banana") | banana is gone |
| Remove and get back | fruits.pop() or fruits.pop(0) | The removed item |
| Delete by index | del fruits[0] | Index 0 is gone |
| Sort | fruits.sort() or fruits.sort(reverse=True) | A to Z, or Z to A |
| Reverse | fruits.reverse() | Order is flipped |
| Check if inside | "apple" in fruits | True |
| Make a copy | fruits.copy() | A new, separate list |