Kodokon kodokon.com

Lists and dictionaries

You create, read, modify, and iterate over lists and dictionaries to organize your data.

10 min · 3 questions

Open this lesson in Kodokon

A list is an ordered collection of values, written inside square brackets [...] with commas. Each element has a position called an index, and numbering starts at 0: the first element is at index 0, the second at index 1, and so on. You read an element by writing the name of the list followed by the index in square brackets.

PYTHON
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[2])
Displays "apple" then "cherry": indexes 0 and 2.

A list is easy to modify: fruits[1] = ... replaces the element at index 1, the append method (a function attached to the list, called with a dot) adds an element at the end, and the len function returns the number of elements. To iterate over the list, that is, to visit each element one after another, you use a for loop.

PYTHON
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"
fruits.append("mango")
print(len(fruits))
for fruit in fruits:
    print(fruit)
Displays 4, then apple, kiwi, cherry, and mango.

A dictionary associates keys with values, just as a phone book associates names with numbers. It's written inside curly braces with key: value pairs. You read a value with its key in square brackets, you modify or add a pair the same way, and the items method lets you iterate over the key/value pairs with a for loop.

PYTHON
person = {"name": "Alice", "age": 30}
print(person["age"])
person["age"] = 31
person["city"] = "Paris"
for key, value in person.items():
    print(key, value)
Displays 30, then the three pairs: name, age (31), and city.

Knowledge check

Make sure you remember the key points of this lesson.

  1. With fruits = ['apple', 'banana'], what is fruits[0]?
    • 'apple'
    • 'banana'
    • An error
  2. How do you add an element to the end of a list?
    • fruits.append('kiwi')
    • fruits.add('kiwi')
    • fruits.push('kiwi')
    • append(fruits, 'kiwi')
  3. In a dictionary, how do you read a value?
    • By its position, like person[0]
    • By its key, like person['name']
    • With the person.value() method