One-sentence summary
A list is a box that holds many values in order, while a dictionary stores each value next to a key, and with loops we can walk through all of this data with just a few lines.
Why it matters
Until now we used separate variables: name1, name2, name3. But if a class has thirty students, do we really write thirty variables? That would be tiring and hard to manage.
Real programs rarely work with a single number. Most of the time they handle a collection of data: a shopping list, the player names in a game, the grades of a class. Lists and dictionaries let us keep these collections tidy. Combined with loops, we can process hundreds of values in only a few lines.
In this lesson I am learning and sharing two core data structures: the list and the dictionary. We will try both with real Python 3 code.
What is a list?
A list is a data structure that holds several values in a specific order. We write the values inside square brackets [ ], separated by commas.
names = ["Ada", "Bora", "Ceren"]
print(names)
This prints:
['Ada', 'Bora', 'Ceren']
A list can hold numbers too:
grades = [85, 90, 78, 100]
print(grades)
Reaching an item: the index
Every item in a list has an index (its position number). One important rule: counting starts at 0. So the first item is 0 and the second item is 1.
names = ["Ada", "Bora", "Ceren"]
print(names[0]) # Ada
print(names[1]) # Bora
print(names[2]) # Ceren
We can also count from the end. -1 always gives the last item:
print(names[-1]) # Ceren
If we ask for an index that does not exist, Python raises an IndexError. In the list above, names[3] does not exist, because the largest index is 2.
Adding an item: append
To add an item to a list later, we use append(). This command adds the new value to the end of the list.
names = ["Ada", "Bora"]
names.append("Ceren")
print(names) # ['Ada', 'Bora', 'Ceren']
We can also start with an empty list and fill it inside a loop:
names = []
names.append("Deniz")
names.append("Ege")
print(names) # ['Deniz', 'Ege']
How many items? len
The len() function tells us how many items are in the list:
names = ["Ada", "Bora", "Ceren"]
print(len(names)) # 3
Walking through a list with a loop
The for loop we learned in the previous lesson is the list's best friend. It visits each item one by one:
names = ["Ada", "Bora", "Ceren"]
for name in names:
print("Hello " + name)
Output:
Hello Ada
Hello Bora
Hello Ceren
Here name represents the next value in the list on every turn. Notice that the loop body is indented by 4 spaces; Python uses this indentation to know which lines belong to the loop.
What is a dictionary?
A dictionary stores each value together with a key. Think of a real dictionary: you look up a word (the key) and find its meaning (the value) next to it.
We write dictionaries inside curly braces { }, in the form key: value.
student = {"name": "Ada", "age": 12, "class": "6-B"}
print(student)
In a list we reached items by their position number; in a dictionary we use the key:
print(student["name"]) # Ada
print(student["age"]) # 12
Adding new information to a dictionary
Adding a new key-value pair is very easy:
student = {"name": "Ada", "age": 12}
student["city"] = "Izmir"
print(student)
Output:
{'name': 'Ada', 'age': 12, 'city': 'Izmir'}
With the same method we can also update an existing value. Writing student["age"] = 13 changes the age.
Example: a student-grade dictionary
In a dictionary the keys can be student names and the values their grades:
grades = {"Ada": 85, "Bora": 90, "Ceren": 78}
print(grades["Bora"]) # 90
To walk through a dictionary and get both the key and the value, we use .items():
grades = {"Ada": 85, "Bora": 90, "Ceren": 78}
for name, grade in grades.items():
print(name + ": " + str(grade))
Output:
Ada: 85
Bora: 90
Ceren: 78
Because grade is a number, we converted it to text with str() before joining it with a string.
Mini practice
Let's write a small program that keeps a class's grades. It should be able to show each grade and also compute the class average.
grades = {"Ada": 85, "Bora": 90, "Ceren": 78}
# Add a new student
grades["Deniz"] = 92
total = 0
for name, grade in grades.items():
print(name + " grade: " + str(grade))
total = total + grade
average = total / len(grades)
print("Class average: " + str(average))
When you run this code, each student's grade is printed in order, then the average is calculated. Because len(grades) gives the number of students, we divide the total by it.
Try it yourself:
- Build a list of your own friends' names and greet each one with a loop.
- Add one more student to the dictionary and watch how the average changes.
Common mistakes
The index starts at 0
Trying to reach the first item with list[1] is a common mistake. Remember: the first item is list[0].
Asking for an index that does not exist
In a three-item list list[3] does not exist, and you get an IndexError. The largest valid index is one less than the length.
Calling a key that is not in the dictionary
If you ask for grades["Efe"] but "Efe" is not in the dictionary, you get a KeyError. Make sure the key exists.
Mixing up lists and dictionaries
A list works with a position number ([0]), a dictionary with a key (["name"]). Both use square brackets, but what you put inside them is different.
Joining a number with text
print("Grade: " + 90) raises an error, because text and a number cannot be joined directly. Convert it to text first with str(90).
Safety note
This lesson is entirely about running your own code on your own computer. Do not run unfamiliar code you find online without understanding it first. Also, do not use real personal details (full names, addresses, phone numbers) of yourself or others in your examples; nicknames are enough for practice.
Lesson summary
- A list holds several values in order; it is written with square brackets
[ ]and its index starts at 0. append()adds an item,len()gives the number of items, and aforloop visits every item.- A dictionary pairs each value with a key; it is written with curly braces
{ }and items are reached by their key. - Writing
dictionary[key] = valueadds new information or updates an existing value. - With
.items()we can loop through both the key and the value of a dictionary at the same time.
Review questions
- In the list
colors = ["red", "green", "blue"], what value doescolors[1]give? - Which command do we use to add an item to the end of a list?
- What does
len(["a", "b", "c", "d"])return? - How do we add an age to the dictionary
student = {"name": "Ada"}? - Which method do we use to loop through both the keys and values of a dictionary?
Answers
"green". Because the index starts at 0,colors[0]is "red" andcolors[1]is "green".append(). For example,colors.append("yellow")adds the new color to the end of the list.4. Thelen()function returns the number of items in the list.- By writing
student["age"] = 12. This line adds a new key-value pair to the dictionary. - We use the
.items()method, in the formfor key, value in dictionary.items():.
Source and verification note
For “Lists and Dictionaries”, verification focuses on whether the relationship between What is a list? and Adding an item: append remains consistent across examples. Code examples follow Python 3 syntax. Small differences may appear between environments, so examples should first be tested in a safe online editor or a local development setup.
Next lesson
Functions: We will learn to name repeated blocks of code and write our own commands.