Module 13: Loops for Data

Processing collections like lists and strings, one item at a time.

🔄 Handling Many Items

Imagine you have a list of names, sensor readings, or letters in a word. Often in AI, we need to perform the same action on each item in a collection.

Doing this manually for every item is tedious and error-prone. Loops are Python's way to automate repetitive tasks over sequences of data. They let us write the action once and apply it to everything. This is a core concept of iteration over data.

⚙️ Why Use Loops?

Loops help us process collections efficiently. Think of it like this:

📦

1. You Have a Collection

A box (list) of items, or letters in a word (string).

⬇️
🔍

2. You Define an Action

What to do with each item (e.g., inspect, count, modify).

⬇️
🔁

3. The Loop Handles Repetition

Python automatically takes each item, performs the action, until all items are processed.

Loops abstract away the manual fetching of each item, letting you focus on the action itself.

✍️ The `for` Loop Syntax

Python's primary loop for iterating over collections is the `for` loop.

Looping Over a List

for item in my_list: # Action(s) using 'item' print(item)

for: Keyword to start the loop.

item: A temporary variable name you choose. It holds the *current* item from the list in each iteration.

in: Keyword connecting the item variable to the collection.

my_list: The list (or other iterable) you want to loop through.

:: The colon marks the start of the indented block of code that repeats.

Indentation is crucial! It defines what code is *inside* the loop.

Looping Over a String

for character in my_string: # Action(s) using 'character' print(character)

The structure is identical to looping over a list!

Here, character is the temporary variable holding each individual character of the string my_string in turn.

A string is treated as a sequence of its characters.

The loop automatically processes the string from the first character to the last.

🎬 Loops in Action

Let's see how these loops work with actual data.

Example: Processing Numbers in a List
numbers = [10, 20, 30] for num in numbers: print(f"Processing: {num}")
Output:
Example: Examining Characters in a String
word = "AI" for letter in word: print(f"Found letter: {letter}")
Output:

🧠 Quick Check!

Module 13 Theory Complete!

Excellent! You've learned how `for` loops automate processing items in lists and strings. This is fundamental for working with data in AI.
Ready to practice iterating? Head to the Practice Zone or challenge yourself with the Advanced Practice.