Python for Beginners: Learn to Code from Zero · Lesson 6 of 10

Lesson 6: Lists and Dictionaries

Store many values together. Use lists for ordered items and dictionaries for labelled data.

Lesson 6: Lists and Dictionaries

Lists

A list holds many values in order, written in square brackets. Counting starts at 0.

cities = ["Kathmandu", "Pokhara", "Biratnagar"]
print(cities[0])
print(cities[2])
print(len(cities))

Output:

Kathmandu
Biratnagar
3

Useful list actions:

cities = ["Kathmandu", "Pokhara"]
cities.append("Lalitpur")     # add to the end
cities.remove("Pokhara")      # remove by value
print(cities)
print("Lalitpur" in cities)

Output:

['Kathmandu', 'Lalitpur']
True

Loop over a list, or work out totals:

marks = [72, 85, 64, 90]
print(sum(marks))
print(max(marks))
print(sum(marks) / len(marks))
for m in marks:
    if m >= 80:
        print(m, "is high")

Output:

311
90
77.75
85 is high
90 is high

Sort a list: sorted(marks) gives a new sorted list.

print(sorted([40, 12, 77, 5]))

Output:

[5, 12, 40, 77]

Dictionaries

A dictionary stores key: value pairs in curly brackets, like a real dictionary where you look up a word to get its meaning.

student = {"name": "Anita", "age": 17, "city": "Butwal"}
print(student["name"])
student["age"] = 18
student["grade"] = "A"
print(student)

Output:

Anita
{'name': 'Anita', 'age': 18, 'city': 'Butwal', 'grade': 'A'}
prices = {"rice": 120, "dal": 150}
for item, price in prices.items():
    print(f"{item}: Rs {price}")

Output:

rice: Rs 120
dal: Rs 150

Lists are for ordered collections of similar things. Dictionaries are for one thing described by labels. Many real programs use a list of dictionaries.

Try it yourself

  1. Make a list of five subjects, add a sixth, and print them one per line.
  2. Find the average of a list of marks.
  3. Create a dictionary for a book (title, author, year) and print each pair.

Next lesson: working with text.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 6: Lists and Dictionaries | MeroSir