for loop in Python: clearly explained!
Hey there! In this article, we’ll talk about the for loop in Python. It allows you to work with collections like lists, strings, sets, and dictionaries:
for name in ["John", "Mia", "Mike"]:
print(name)Output:
John
Mia
Mikefor loop with range
If you want to run a block of code a specific number of times, you can use the range function.
By default, the range function returns a sequence of numbers, starting from zero:
for i in range(3):
print(i)Program output:
0
1
2You can also specify a starting number:
for i in range(2, 5):
print(i)Output:
2
3
4You can also adjust the step of the loop by passing a third argument to the range function:
for i in range(2, 9, 3):
print(i)Output:
2
5
8What’s the output of this Python code?
for i in range(3, 15, 4):
print(i)for loop through a string
In Python, you can use the for loop to iterate through a string. The code block will run for each character:
name = "John"
for letter in name:
print(letter)Output:
J
o
h
nThe break statement
Python allows you to stop the loop at any time. You just use the break keyword:
for i in range(10):
if i == 3:
print("Not going beyond this")
break
print(i)Output:
0
1
2
Not going beyond thisThe continue statement
If you don’t want to stop the loop entirely but just skip one iteration, you can use the continue keyword:
for i in range(5):
if i == 3:
print("3 won't do")
continue
print(i)Output:
0
1
2
3 won't do
4From the example, you can see that the for loop continued running, skipping just one element. In this instance, you could use just if-else:
for i in range(5):
if i == 3:
print("3 won't do")
else:
print(i)But I prefer the version with continue, especially when we have lots of instructions that need to be executed in the loop. continue helps remove the nesting level that arises from using else.
What’s the output of the following Python code?
for i in range(5):
if i == 2:
continue
elif i == 4:
print("Wrapping it up")
break
print(i)for-else
Did you know that the else keyword can be used not only with if but also with for? Check this out:
for i in range(3):
print(i)
else:
print("Done!")Output:
0
1
2
Done!But now, let’s add break:
for i in range(3):
if i == 2:
break
print(i)
else:
print("Done!")Now the output is different:
0
1There’s no “Done!” this time. That’s because the else after for only executes if the loop processed all items without hitting a break. And by the way, continue doesn’t affect the else:
for i in range(3):
if i == 2:
continue
print(i)
else:
print("Done!")Output:
0
1
Done!What will be displayed?
for i in range(5):
if i % 3 == 0:
continue
elif i == 4:
break
print(i)
else:
print("Done!")nested loops
You can use a for loop inside another for loop:
for i in range(1, 3):
for j in range(1, 3):
print(i, "*", j, "=", i * j)Output:
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4And yeah, you can nest them as deep as you like.
The pass statement
If you ever think “I don’t really want to do anything in this loop”, then pass is your friend:
for i in range(100):
passThis code won’t do a thing.
Using enumerate with for
Ever needed to know the index of an item in a for loop? Just wrap the list in the enumerate function:
names = ["John", "Mia", "Mike"]
for i, name in enumerate(names):
print(i, name)Output:
0 John
1 Mia
2 MikeYou can even choose the starting number for
enumeratewith thestartargument.
What’s the output of this Python code?
students = ["James", "Ava", "Oliver"]
for idx, student in enumerate(students, start=1):
print(idx, student)Using a for loop with dictionaries
Need to loop through the values in a dictionary? No worries. The for loop handles this with ease:
ages = {
"John": 18,
"Mia": 22,
"Mike": 26,
}
for name in ages:
print(name, ages[name])Output:
John 18
Mia 22
Mike 26With this, we can directly get both the name and age:
for name, age in ages.items():
print(name, age)Output:
John 18
Mia 22
Mike 26If we’re only interested in the ages, we can use the .values() method:
for age in ages.values():
print(age)Output:
18
22
26Iterating in reverse order
If for some reason we want to loop through items in reverse, we can wrap the items in the reversed function:
for i in reversed(range(1, 4)):
print(i)Output:
3
2
1For the range, we can simply pass a negative step to get items in reverse:
for i in range(3, 0, -1):
print(i)The output for this program is identical to the previous one.
What will be displayed on the screen?
for i in reversed(range(3)):
print(i)One-liner for loops
If you need to execute only one instruction, you can use the shorthand version of the for loop:
for i in range(3): print(i)Output:
0
1
2Exercises
-
Basic
forloop usage with different collection types:
Use different collection types (list, string, set, dictionary) and write a Python program where you use aforloop to display each collection element. Your program should handle each collection type correctly. -
Exploring the
rangefunction with different parameters:
a) Write a program that uses theforloop andrangeto display numbers from 5 to 15.
b) Write a program that displays every third number in the range of 10 to 25. -
Controlling loop execution with
break:
Write a program with a list of 10 names. Your task is to loop through the list of names using aforloop, and as soon as you encounter the name “Dima”, the program should display “Found Dima!” and exit the loop. If “Dima” isn’t in the list, the program should display “Dima not found”.
Discussion