In this short post, you’ll see 3 simple examples of For Loop in Python.
In particular, the following 3 cases will be reviewed:
- Looping over a list
- Adding a break
- Looping across multiple lists
3 Examples of For Loop in Python
Example 1: Looping over a List
Let’s suppose that you created a list of integers:
my_list = [22, 57, 15, 8, 29]
Now let’s say that you want to increase each value in the list by 1.
You can then use the following loop to achieve this goal:
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
Suppose that you now have the following list:
my_list = ['red', 'red', 'red', 'red', 'blue', 'blue', 'yellow', 'blue', 'blue']
What if you want to add a break when looping over that list?
For example, let’s say that you want to apply a break once the color is equal to ‘yellow.’
In that case, no additional colors would be added once you reached the ‘yellow’ color.
Here is the code that you may apply in Python for our example:
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
For the final case, let’s review 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]
You have seen how to apply for loop in Python. You may also want to check the following guide that explains how to apply a while loop in Python.