← Python Crash Course

PCC·04 · Chapter record

Working with Lists

Chapter 4 — looping, generating, slicing, copying, and locking lists

Done

Five sessions on doing real work with lists: looping through every item, generating numeric lists with range(), grabbing a slice, copying a list properly, and tuples — lists that refuse to change. Each one explains the concept, lists the key terms, then gives you exercises — try them yourself before revealing the code.

4.1

for Loops

  • A for loop repeats the same action for every item in a list, without repetitive code and without caring how long the list is.
  • for magician in magicians: pulls one name at a time from the list and assigns it to magician — every indented line under it runs once per item.
  • You can write as many indented lines as you like inside the loop — each one runs on every single pass.
  • A line after the loop that isn't indented runs only once, after the loop finishes — perfect for a summary message.
  • Python uses indentation, not braces, to know what's inside the loop — forget to indent and you get an IndentationError.
for loop
repeats a block of code once for each item in a list
loop variable
the temporary name (magician, cat, item…) holding the current item
IndentationError
raised when Python expects an indented line and doesn't find one
Activity 1

Store three foods you like in a list called pizzas, then use a for loop to print a sentence about each one.

Activity 2

Store a few animals in a list, then use a for loop to print one fact about each animal.

Activity 3

Inside a loop over a list of names, print two lines per person — a greeting, then a farewell with a blank line after — then add one summary line after the loop that runs only once.

▶ Loop Tracer