🔄

04c The `for` Loop

Sep 24, 2025

Overview

This lecture explains how for loops in Python work, especially for iterating through lists and dictionaries, and introduces related concepts like temporary variables, naming conventions, and type casting.

While Loop Recap

  • A while loop needs an initializer, a boolean test, and an increment to iterate through a list.
  • In Python, index += 1 is a shortcut for index = index + 1.
  • The plus operator (+) is overloaded to work with numbers and strings.

For Loops in Python

  • Python's for loop automatically handles initialization, condition, and increment for list iteration.
  • Syntax: for variable in list: executes the loop body for each item in the list.
  • The loop variable (e.g., flavor) is a temporary bucket that holds each value in turn.
  • The variable name is arbitrary; Python does not infer singular/plural relationships.

Looping Patterns and Naming Conventions

  • Common pattern: for item in items, where item is singular and items is plural.
  • Variable names are for human understanding; Python does not interpret meaning.

For Loops with Dictionaries

  • Iterating a dictionary with for key in dict: loops over the keys.
  • To access values, use dict[key] inside the loop.
  • Use dict.values() to iterate values and dict.items() to get key-value pairs as tuples.
  • In loops like for key, value in dict.items():, parallel assignment unpacks each tuple.

Enumerate with Lists

  • Use enumerate(list) to loop over both indexes and values.
  • Syntax: for index, value in enumerate(list):
  • enumerate is a standalone function, not a list method.

Data Types and Type Casting

  • Mixing integers and strings in concatenation causes a TypeError.
  • Convert (cast) integers to strings with str(index) to concatenate them in print statements.
  • Casting is temporary; the original variable's type remains unchanged.

Key Terms & Definitions

  • For loop — a loop structure that iterates over each item in a sequence.
  • Temporary variable — a short-lived variable that holds each item during iteration.
  • Overloaded operator — an operator (like +) that behaves differently based on operand types.
  • Method — a function that belongs to an object (like dict.items()).
  • Tuple — an immutable sequence type, used for pairing key-value or index-value.
  • Enumerate — a function to get both index and value from a list.
  • Casting — converting a value from one type to another (e.g., integer to string).

Action Items / Next Steps

  • Practice writing for loops with lists and dictionaries.
  • Use enumerate and dict.items() to access indexes and key-value pairs.
  • Prepare for next lecture on objects and comprehensions.