Lists & Dictionaries
The two most useful collections in Python. Lists hold an ordered sequence of items. Dictionaries hold lookup pairs — a key and a value.
Lists
Square brackets, items separated by commas:
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(len(fruits)) # number of items: 3
Indexing — getting an item by position
print(fruits[0]) # apple — counting starts at 0!
print(fruits[1]) # banana
print(fruits[-1]) # cherry — negative numbers count from the end
Slicing — getting a chunk
print(fruits[0:2]) # ['apple', 'banana'] — items 0 and 1
print(fruits[:2]) # same as above
print(fruits[1:]) # ['banana', 'cherry']
Changing a list
fruits.append("date") # add to the end
fruits.insert(0, "apricot") # insert at position 0
fruits.remove("banana") # remove first matching item
fruits[1] = "avocado" # overwrite item at position 1
print(fruits)
Useful list things
nums = [3, 1, 4, 1, 5, 9]
print(sum(nums)) # 23
print(min(nums)) # 1
print(max(nums)) # 9
print(sorted(nums)) # [1, 1, 3, 4, 5, 9]
print(5 in nums) # True — membership check
Looping over a list
for fruit in fruits:
print("-", fruit)
Dictionaries
Curly braces, with key: value pairs. Use a dict when each item has a meaningful label.
person = {
"name": "Sam",
"age": 34,
"email": "sam@example.com",
}
print(person["name"]) # Sam
print(person["age"]) # 34
Adding, updating, removing
person["city"] = "Belfast" # add new key
person["age"] = 35 # update existing key
del person["email"] # remove a key
print(person)
Safe lookups with .get()
If you ask for a key that doesn't exist with square brackets, you get a KeyError.
.get() returns None instead (or whatever default you supply):
print(person.get("phone")) # None
print(person.get("phone", "unknown")) # unknown
Looping over a dictionary
for key in person:
print(key, "=>", person[key])
# Or get key + value at once:
for key, value in person.items():
print(f"{key}: {value}")
When to use which?
- List — when order matters and items are similar (a list of names, prices, scores).
- Dictionary — when each item has a label and you want to look it up by that label (a person record, a config, a count of words).
A worked example: counting words
text = "the cat sat on the mat the mat was warm"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
{'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 2, 'was': 1, 'warm': 1}