For Loops with range() and Iterating Over Collections
A for loop in Python is used to iterate over the elements of a sequence or other iterable (like lists, strings, tuples, dictionaries, sets, etc.), executing a block of code for each element.
Python’s for loop works more like the “for-each” loop in other languages rather than the traditional C-style loop with an index.
This means:
-
No need to manually manage an index or increment a counter.
-
Python handles stepping through the sequence automatically.
Iterating Over a Sequence
Syntax:
for <variable> in <sequence>:
<block of code>
-
On each iteration:
-
<variable>is assigned the next element from<sequence>. -
The code block executes using that value.
-
-
Loop continues until all elements are processed.
Example – looping through a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I have a", fruit)
Output:
I have a apple
I have a banana
I have a cherry
💡 The loop runs 3 times (once for each fruit). No index like i++ is needed.
Example – looping through a string:
for ch in "PYTHON":
print(ch, end=" ")
Output:
P Y T H O N
Example – looping through a dictionary:
mydict = {"name": "Alice", "age": 25}
for key, val in mydict.items():
print(key, ":", val)
Output:
name : Alice
age : 25
💡 Tip:
If you need both the index and value, use enumerate():
for idx, val in enumerate(["a", "b", "c"]):
print(idx, val)
The range() Function for Numeric Loops
range() generates a sequence of numbers, which you can loop over.
Basic example:
for i in range(5): # 0 to 4
print("Iteration", i)
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Custom start and step:
print(list(range(2, 6))) # [2, 3, 4, 5]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, ..., 1]
Example – summing numbers:
total = 0
for n in range(1, 6): # 1 to 5
total += n
print("Sum of 1 to 5 is", total)
Output:
Sum of 1 to 5 is 15
Example – ignoring the loop variable:
for _ in range(3):
print("Hello")
Output:
Hello
Hello
Hello
Break and Continue
-
break→ Stop the loop immediately. -
continue→ Skip current iteration, go to next.
Example – using break & continue:
numbers = [1, 3, 7, 10, 15]
for num in numbers:
if num == 10:
print("Found 10! Stopping the search.")
break
if num % 2 == 0:
continue
print("Odd number:", num)
Output:
Odd number: 1
Odd number: 3
Odd number: 7
Found 10! Stopping the search.
💡 Key points:
-
break→ jumps out of the loop entirely. -
continue→ skips to the next iteration. -
Works in both
forandwhileloops.
Recap:
-
Use
for item in collectionwhen iterating over items. -
Use
for i in range(n)when looping a fixed number of times. -
Use
enumerate()if you need an index. -
Use
breakto stop early,continueto skip iterations.
Mini-Exercise:
-
Loop over the string
"LOOP"and print each character on its own line. -
Use
range(1, 11)to print all even numbers from 1 to 10. -
Write a loop that goes through a list and stops if it finds
"STOP".
