PyPython · Lesson 5 of 14

Lists, Dicts & Sets

Python's built-in collections are so good you'll rarely need anything else. Lists, dicts, and sets cover 95% of real-world needs.

Lists are ordered, mutable sequences. They're Python's workhorse collection type. You can put anything in a list — including other lists.

Python
# Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[0])      # apple (0-indexed)
print(fruits[-1])     # cherry (negative index = from end)
print(fruits[1:3])    # ['banana', 'cherry'] (slicing)

# Mutating lists
fruits.append("date")           # add to end
fruits.insert(1, "avocado")    # insert at index 1
fruits.remove("banana")         # remove by value
popped = fruits.pop()           # remove and return last item
fruits.sort()                   # sort in-place

# List comprehension — the Pythonic way to build lists
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
print(squares)   # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Useful list methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(len(numbers))      # 8
print(sum(numbers))      # 31
print(min(numbers))      # 1
print(max(numbers))      # 9
print(numbers.count(1))  # 2

Dictionaries map keys to values. As of Python 3.7+, they maintain insertion order. They're used everywhere — for config, JSON-like data, and anything that needs fast key-based lookup.

Python
# Dictionaries
person = {
    "name": "Alice",
    "age": 30,
    "city": "Paris",
}

print(person["name"])              # Alice
print(person.get("country", "Unknown"))  # Unknown (safe default)

# Mutating dicts
person["email"] = "alice@example.com"   # add or update
del person["city"]                        # remove key

# Iterating
for key in person:
    print(key, "->", person[key])

for key, value in person.items():
    print(f"{key}: {value}")

# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Sets — unordered, unique values
tags = {"python", "web", "backend", "python"}
print(tags)   # {'python', 'web', 'backend'} — duplicate removed

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b)   # intersection: {3, 4}
print(a | b)   # union: {1, 2, 3, 4, 5, 6}
print(a - b)   # difference: {1, 2}
◆ Note
Use a list when order matters. Use a dict when you need to look things up by name. Use a set when you only care about unique membership. Picking the right data structure is half of writing good code.