Lesson 11 of 21 · 4 min
for Loop — Iterate Over a Sequence
The WHY — Why for Loops?
The for loop is for when you have a collection of things and you want to do something with each one. "For each student in the class, print their name." "For each product in the cart, add its price to the total." You know what you are iterating over.
for Loop Over a List
fruits = ["apple", "banana", "mango", "grape"] # list of fruits
for fruit in fruits: # for each item in the fruits list...
print(fruit) # ...print that item
Output: apple banana mango grape
Python automatically moves through the list one item at a time, putting each item into the variable fruit.
for Loop Over a String (Character by Character)
word = "Python" # a 6-character string
for letter in word: # for each character in the word...
print(letter) # ...print just that character
Output: P y t h o n
range() — Generating a Sequence of Numbers
range() generates a sequence of numbers. It is used with for loops when you need to repeat something a specific number of times.
| Syntax | What It Generates | Example |
|---|---|---|
range(stop) | 0, 1, 2, ..., stop-1 | range(5) → 0,1,2,3,4 |
range(start, stop) | start, start+1, ..., stop-1 | range(1,6) → 1,2,3,4,5 |
range(start, stop, step) | start, start+step, ... | range(0,10,2) → 0,2,4,6,8 |
# range(stop) — count from 0 up to (but not including) stop
for i in range(5): # i takes values 0, 1, 2, 3, 4
print(i, end=" ") # print each on same line, separated by space
print() # print blank line after
# range(start, stop) — count from start up to (not including) stop
for i in range(1, 6): # i takes values 1, 2, 3, 4, 5
print(i, end=" ")
print()
# range(start, stop, step) — count by step
for i in range(0, 10, 2): # i takes even values 0, 2, 4, 6, 8
print(i, end=" ")
print()
# Counting backwards
for i in range(5, 0, -1): # i goes 5, 4, 3, 2, 1 (step of -1 = backwards)
print(i, end=" ")
print()
Output: 0 1 2 3 4 1 2 3 4 5 0 2 4 6 8 5 4 3 2 1
Practical for Loop — Sum and Count
scores = [85, 92, 78, 65, 88, 95, 70] # list of exam scores
total = 0 # start total at zero
for score in scores: # go through each score one at a time
total = total + score # add each score to the running total
average = total / len(scores) # divide total by number of scores
print(f"Total: {total}") # display the sum
print(f"Average: {average:.1f}") # display average rounded to 1 decimal
Output: Total: 573 Average: 81.9
enumerate() — Getting Both Index and Value
Sometimes you need both the position number AND the value. enumerate() gives you both:
students = ["Priya", "Ahmed", "Ravi", "Sara"] # list of student names
for index, name in enumerate(students): # get BOTH position and name
print(f"{index + 1}. {name}") # print numbered list (starting from 1)
Output: 1. Priya 2. Ahmed 3. Ravi 4. Sara
Without enumerate(), you would need an extra variable and manual incrementing. enumerate() makes it clean.
