Collections & Loops

Python collections (list, dict, set, tuple) and iteration patterns.

Collections

List

items = []                   # empty list
items = [1, 2, 3]

items.append(4)              # add
items.pop()                  # remove last
items.remove(2)              # remove by value
items[0]                     # access by index

Dict

person = {}                  # empty dict
person = {"name": "Ada", "age": 30}

person["name"]               # access
person["city"] = "ATH"       # set
del person["city"]           # delete
person.get("name", "unknown")# safe access

Set & Tuple

unique = {1, 2, 3}          # set — no duplicates
coords = (0, 1)              # tuple — immutable

Loops

for

for item in items:
    print(item)

for i in range(10):
    print(i)

for key, value in person.items():
    print(key, value)

while

running = True
while running:
    result = do_work()
    if not result:
        running = False

break & continue

for i in range(10):
    if i % 2 == 0:
        continue        # skip even
    if i > 7:
        break           # exit loop

Comprehensions

squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
cubes = {x: x**3 for x in range(5)}
unique_len = {len(w) for w in words}

Next: String Manipulation