Python Lists Missions 0/6

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

Lists in real life

You already use lists every day. Programmers use Python lists to build things like these:

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

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)
List BuilderBuild a list and watch the lockers appear.

    

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])
Index Explorer

    

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

snacks = ["chips", "cookies"]
snacks.append("candy")
print(snacks)

snacks.insert(1, "popcorn")
print(snacks)

snacks.extend(["nuts", "raisins"])
print(snacks)

Remove items

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?

ToolWhat it doesExample
list[i] = xReplaces the item at index icolors[1] = "pink"
append(x)Adds one item at the endsnacks.append("candy")
insert(i, x)Adds one item at index isnacks.insert(0, "nuts")
extend(list)Adds many items at the endsnacks.extend(["a", "b"])
remove(x)Removes the first item equal to xpets.remove("cat")
pop(i)Removes item at index i and gives it backpets.pop(0)
del list[i]Deletes item at index idel pets[0]
sort() / reverse()Changes the orderscores.sort()
Update Lab
Pick a tool above and see what happens to the lockers.

The Python code you have run so far:


  

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])
Fix: There are 3 items, so the indexes are 0, 1 and 2. Use fruits[2] or fruits[-1].
Mistake 2: Forgetting the quotes
names = [Ana, Budi]
print(names)
Fix: Text needs quotes: names = ["Ana", "Budi"].
Mistake 3: Round brackets instead of square brackets
fruits = ["apple", "banana"]
print(fruits(0))
Fix: Use square brackets to open a locker: fruits[0].
Mistake 4: Removing something that is not there
fruits = ["apple", "banana"]
fruits.remove("mango")
Fix: Check first with "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))
Fix: 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)
Fix: 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"
Fix: Text cannot be changed like this. Lists can! Make a new text: 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)
Fix: 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.

Start with:
Tip: press Ctrl + Enter to run.
Press Run to see the output.

This mini Python runs one simple command per line, like a real Python file: only print() shows output. Loops and if-statements come in a later lesson.

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...CodeResult
Make a listfruits = ["apple", "banana"]A list with 2 items
Make an empty listtodo = []No items yet
Get the first itemfruits[0]'apple'
Get the last itemfruits[-1]'cherry'
Count the itemslen(fruits)3
Get a slicefruits[0:2]['apple', 'banana']
Change an itemfruits[0] = "kiwi"Index 0 is now kiwi
Add at the endfruits.append("mango")mango is last
Add at a placefruits.insert(1, "pear")pear is at index 1
Add many itemsfruits.extend(["a", "b"])a and b are at the end
Remove by valuefruits.remove("banana")banana is gone
Remove and get backfruits.pop() or fruits.pop(0)The removed item
Delete by indexdel fruits[0]Index 0 is gone
Sortfruits.sort() or fruits.sort(reverse=True)A to Z, or Z to A
Reversefruits.reverse()Order is flipped
Check if inside"apple" in fruitsTrue
Make a copyfruits.copy()A new, separate list