You create, read, modify, and iterate over lists and dictionaries to organize your data.
Open this lesson in KodokonA 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.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[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.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"
fruits.append("mango")
print(len(fruits))
for fruit in fruits:
print(fruit)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.
person = {"name": "Alice", "age": 30}
print(person["age"])
person["age"] = 31
person["city"] = "Paris"
for key, value in person.items():
print(key, value)fruits = ['apple', 'banana'], what is fruits[0]?