Chapter 4: Working with Lists

Iteration is where lists become powerful. Process any size list with the same code.

For Loops

servers = ['web-01', 'web-02', 'db-01']
for server in servers:
    print(f"Checking {server}")
Checking web-01
Checking web-02
Checking db-01

Convention: singular variable for the item, plural for the list.

for cat in cats:
for user in users:
for item in items:

Multiple Statements

Everything indented runs for each item:

servers = ['web-01', 'web-02', 'db-01']
for server in servers:
    print(f"Connecting to {server}...")
    print(f"Health check: {server} OK\n")

print("All servers checked.")  (1)
1 Unindented = runs once, after loop completes

Indentation Errors

Python uses indentation to define blocks. Mistakes are syntax errors:

for server in servers:
print(server)  # IndentationError: expected an indented block
for server in servers:
    print(server)
    print("Done")  # runs for each
print("Done")      # runs once after

Numerical Lists

range()

Generate sequences of numbers:

for n in range(5):
    print(n)
# 0, 1, 2, 3, 4

for n in range(1, 6):  # start, stop (exclusive)
    print(n)
# 1, 2, 3, 4, 5

for n in range(0, 10, 2):  # start, stop, step
    print(n)
# 0, 2, 4, 6, 8

Convert to list:

numbers = list(range(1, 6))
# [1, 2, 3, 4, 5]

Numeric Functions

nums = [1, 2, 3, 4, 5]
min(nums)  # 1
max(nums)  # 5
sum(nums)  # 15

List Comprehensions

Create lists in one line. Pythonic and fast.

# Traditional way
squares = []
for n in range(1, 6):
    squares.append(n ** 2)

# Comprehension
squares = [n ** 2 for n in range(1, 6)]
# [1, 4, 9, 16, 25]

With condition:

# Only even numbers
evens = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]

Real-world example:

servers = ['web-01', 'web-02', 'db-01', 'db-02']

# All web servers
web_servers = [s for s in servers if s.startswith('web')]
# ['web-01', 'web-02']

# Uppercase names
upper = [s.upper() for s in servers]
# ['WEB-01', 'WEB-02', 'DB-01', 'DB-02']

Slices

Access portions of a list:

servers = ['web-01', 'web-02', 'web-03', 'db-01', 'db-02']

servers[0:3]   # ['web-01', 'web-02', 'web-03']
servers[:3]    # same - start defaults to 0
servers[2:]    # ['web-03', 'db-01', 'db-02'] - to end
servers[-2:]   # ['db-01', 'db-02'] - last 2
servers[::2]   # ['web-01', 'web-03', 'db-02'] - every 2nd

Slice syntax: [start:stop:step]

Loop Over a Slice

# Process only first 3
for server in servers[:3]:
    print(server)

Copy a List

Assignment creates a reference, not a copy:

# Wrong - both point to same list
servers_a = ['web-01', 'web-02']
servers_b = servers_a
servers_b.append('web-03')
print(servers_a)  # ['web-01', 'web-02', 'web-03'] - modified!

Use slice to copy:

# Right - independent copy
servers_a = ['web-01', 'web-02']
servers_b = servers_a[:]  (1)
servers_b.append('web-03')
print(servers_a)  # ['web-01', 'web-02'] - unchanged
1 [:] creates a shallow copy

Tuples

Immutable lists. Use parentheses:

dimensions = (1920, 1080)
dimensions[0]  # 1920
dimensions[0] = 1280  # TypeError: cannot modify tuple

Single-element tuple needs trailing comma:

single = (42,)   # tuple
not_tuple = (42) # just an integer

When to use tuples: - Data that shouldn’t change (coordinates, RGB values, config) - Dictionary keys (lists can’t be keys) - Function return values

def get_dimensions():
    return (1920, 1080)  # return multiple values

width, height = get_dimensions()  # unpack

Quick Reference

Pattern Code

For loop

for item in items:

Range

range(stop), range(start, stop, step)

List from range

list(range(5))

Comprehension

[expr for item in items]

Conditional comp

[x for x in items if condition]

Slice

items[start:stop:step]

Copy list

items[:] or items.copy()

Tuple

(a, b, c)

Exercises

4-1. Pizzas

Create a list of pizzas. Loop through and print "I like X pizza."

4-2. Range

  • Print numbers 1-20

  • Print 1-1000000, calculate sum

  • Print odd numbers 1-20

4-3. Comprehensions

Create using comprehensions: - Cubes of 1-10 - First 10 multiples of 7 - Even numbers from 1-50

4-4. Slices

Create a list of 10 items. Print: - First 3 - Middle 3 - Last 3

4-5. Tuple

Create a buffet menu as tuple. Try to modify it (see error). Then reassign the whole tuple.

Summary

  • for item in list: iterates through all elements

  • Indentation defines the loop body

  • range() generates numeric sequences

  • List comprehensions: [expr for x in items if cond]

  • Slices: list[start:stop:step]

  • list[:] copies a list

  • Tuples are immutable lists

Next: Conditionals with if statements.