← Python course

Lesson 05

Lists and collections

Storing many things under one name, and looking them up.

You've already seen a list (names = ["Yohana", "Rodas"]). Now let's actually use one.

Loading editor…

A list is an ordered collection. fruits[0] gets the first item — remember, counting starts at 0, so [0] is "mango"'s neighbor, not the second one. len(fruits) tells you how many items are in it.

Lists can grow and shrink:

Loading editor…

.append(...) adds something to the end. .remove(...) takes the first matching item out. These are methods — functions that belong to a specific list, written with a dot.

There's also the dictionary — instead of counting positions, you look things up by name:

Loading editor…

Think of a dictionary as labeled boxes instead of a numbered shelf. student["age"] means "open the box labeled age."

Loop over a list the same way you looped over numbers:

Loading editor…

Your turn

Make a list of your three favorite subjects. Loop over it and print each one with its position, like "1. Python". Hint: for i, subject in enumerate(subjects): gives you both the position and the value — and i starts at 0, so you'll want i + 1 to print starting from 1.

Loading editor…

Next lesson: functions — teaching the computer a new trick it can reuse.