In this short post, you’ll see 3 simple examples of For Loop in Python:
- Looping over a list
- Adding a break
- Looping across multiple lists
3 Examples
Example 1: Looping over a List
Suppose that you created a list of integers:
my_list = [22, 57, 15, 8, 29]
To increase each value in the list by 1 using a For Loop:
my_list = [22, 57, 15, 8, 29]
sum_list = []
for i in my_list:
sum_list.append(i + 1)
print(sum_list)
You’ll now see that each value in the list increased by 1:
[23, 58, 16, 9, 30]
Example 2: Adding a Break
Assume that you now have the following list:
my_list = ["red", "red", "red", "red", "blue", "blue", "yellow", "blue", "blue"]
To add a break once the color is equal to “yellow”:
my_list = ["red", "red", "red", "red", "blue", "blue", "yellow", "blue", "blue"]
new_list = []
for i in my_list:
new_list.append(i)
if i == "yellow":
break
print(new_list)
You’ll notice that the “yellow” color is the last color in the list:
['red', 'red', 'red', 'red', 'blue', 'blue', 'yellow']
Example 3: Looping Across Multiple Lists
Now assume that you have the following two lists that contain integers:
list_x = [12, 8, 6]
list_y = [2, 3, 4]
You can then multiply the values across the two lists:
list_x = [12, 8, 6]
list_y = [2, 3, 4]
mul_list = []
for x in list_x:
for y in list_y:
mul_list.append(x * y)
print(mul_list)
Here is the result:
[24, 36, 48, 16, 24, 32, 12, 18, 24]
Check the following guide that explains how to apply a While Loop in Python.