The for Loop
Overview
Use the for loop to iterate through sequences such as strings, lists, and ranges. You'll understand how iteration works behind the scenes and how to combine it with built-in functions like range() for efficiency.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What a for loop is: Understand how for loops iterate through sequences.
- Using range(): Learn how to use range() to create sequences of numbers.
- Iterating through strings: Discover how to loop through each character in a string.
- Iterating through lists: Master looping through lists of items.
Why This Matters
The for loop is the most common type of loop in Python. It's perfect when you know what you want to iterate through - whether it's a range of numbers, characters in a string, or items in a list. It's cleaner and easier to read than while loops when you're working with sequences.
Step 1: What Is a for Loop?
A for loop repeats code for each item in a sequence. Think of it like going through a shopping list one item at a time, or reading a book page by page. The loop automatically goes through each item in the sequence - you don't need to manually track counters like with while loops.
for variable in sequence:
# Code to repeat for each item
print(variable)
# More code here
Start with for
The keyword for tells Python you're starting a loop that iterates through a sequence.
Choose a Variable Name
After for, write a variable name. This variable will hold each item from the sequence, one at a time.
Use in and the Sequence
Write in followed by the sequence you want to iterate through (like a string, list, or range).
Add a Colon and Indent
End with a colon : and indent the code block. This code runs once for each item in the sequence.
Key Concept: The for loop automatically handles the iteration process. You don't need to manually increment a counter or check conditions - Python does it for you. The loop runs exactly as many times as there are items in the sequence.
Mini Practice #1: Your First for Loop
Try It YourselfTry this simple for loop that prints each number from 1 to 5:
What happened? Python created a sequence of numbers from 1 to 5 using range(1, 6). The for loop then went through each number in this sequence. On the first iteration, i was set to 1, and "Number: 1" was printed. On the second iteration, i was set to 2, and "Number: 2" was printed. This continued for each number in the sequence (1, 2, 3, 4, 5). Notice how you didn't need to manually increase a counter or check a condition - the for loop handled everything automatically!
Step 2: Understanding range()
The range() function creates a sequence of numbers. It's perfect for when you want to loop a specific number of times. There are three ways to use it:
range(stop)
Creates numbers from 0 up to (but not including) stop.
range(5)
# Creates: 0, 1, 2, 3, 4
Runs 5 times
range(start, stop)
Creates numbers from start up to (but not including) stop.
range(1, 6)
# Creates: 1, 2, 3, 4, 5
Runs 5 times
range(start, stop, step)
Creates numbers from start to stop, counting by step.
range(0, 10, 2)
# Creates: 0, 2, 4, 6, 8
Counts by 2s
Important: The stop value is NOT included in the range. So range(1, 6) gives you 1, 2, 3, 4, 5 (not 6). This is consistent with Python's indexing, which starts at 0. Think of it as "up to but not including" the stop value.
Mini Practice #2: Different range() Examples
Try It YourselfTry different ways to use range():
What happened? The first loop used range(5), which creates numbers from 0 to 4 (5 numbers total). The second loop used range(2, 6), which creates numbers from 2 to 5 (starting at 2, stopping before 6). The third loop used range(0, 10, 2), which creates numbers from 0 to 8, counting by 2s (0, 2, 4, 6, 8). Notice how the step parameter lets you skip numbers - this is useful for counting by twos, threes, or any interval you want!
Step 3: Iterating Through Strings
You can use a for loop to go through each character in a string. This is very useful for processing text character by character.
word = "Python"
for char in word:
print(char)
How It Works
When you loop through a string, Python goes through each character one at a time. The variable char (or whatever name you choose) holds the current character. On the first iteration, char is "P". On the second, it's "y". This continues for each character in the string.
Mini Practice #3: Looping Through Strings
Try It YourselfTry looping through a string:
What happened? Python went through each character in the string "Alice" one at a time. On the first iteration, letter was "A" and it was printed. On the second iteration, letter was "l" and it was printed. This continued for each character: "A", "l", "i", "c", "e". Each character was printed on its own line. This is how you can process text character by character!
Step 4: Iterating Through Lists
You can also use a for loop to go through each item in a list. Lists are collections of items, and for loops make it easy to process each item.
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")
How It Works
When you loop through a list, Python goes through each item one at a time. The variable name (or whatever name you choose) holds the current item. On the first iteration, name is "Alice". On the second, it's "Bob". The loop automatically handles going through all items in the list.
Mini Practice #4: Looping Through Lists
Try It YourselfTry looping through a list:
What happened? Python went through each item in the list fruits one at a time. On the first iteration, fruit was "apple" and "I like apple" was printed. On the second iteration, fruit was "banana" and "I like banana" was printed. On the third iteration, fruit was "orange" and "I like orange" was printed. Then the loop was done - it had processed all three items in the list. This is much cleaner than manually accessing each item!
Step 5: for Loop vs. while Loop
Both for and while loops repeat code, but they're used for different situations:
Use for When:
You know what you're iterating through - a range, string, list, or other sequence.
# Iterating through a sequence
for i in range(10):
print(i)
for char in "Python":
print(char)
Cleaner and easier to read
Use while When:
You don't know how many times to repeat - it depends on a condition changing.
# Repeating until condition changes
count = 0
while count < 10:
print(count)
count = count + 1
More flexible for unknown iterations
Rule of Thumb: If you're working with a sequence (range, string, list), use a for loop. If you're repeating until a condition changes and you don't know how many times it will run, use a while loop. Most of the time, if you can use a for loop, it's the better choice because it's cleaner and less error-prone.
End-of-Lesson Exercises
Exercise 1: Use range() in a for Loop
Write a for loop that uses range(1, 6) to print the numbers 1 through 5.
Use for i in range(1, 6): followed by an indented print statement.
Exercise 2: Loop Through a List
Create a list: colors = ["red", "blue", "green"]. Write a for loop that prints each color.
Use for color in colors: followed by an indented print statement.