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
- Make a list of five subjects, add a sixth, and print them one per line.
- Find the average of a list of marks.
- Create a dictionary for a book (title, author, year) and print each pair.
Next lesson: working with text.

Comments
Loading comments…