In this short post, I’ll show you 4 simple examples of for loop in Python.
In particular, I’ll review the following 4 cases:
- Looping over a list
- Adding a break
- Performing arithmetic operations
- Looping across multiple lists
4 Examples of For Loop in Python
Example 1: Looping over a List
Let’s suppose that you created a list of colors:
myList = ['red','red','red','red','blue','blue','yellow','blue','blue']
You can then loop over that list as follows:
myList = ['red','red','red','red','blue','blue','yellow','blue','blue'] for colors in myList: print (colors)
All the colors on that list will then get printed:
Example 2: Adding a Break
What if you want to add a break?
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 get printed once you reached the ‘yellow’ color.
Here is the code that you may apply in Python for our example:
myList = ['red','red','red','red','blue','blue','yellow','blue','blue'] for colors in myList: print (colors) if colors == 'yellow': break
You’ll notice that the ‘yellow’ color is the last color to be printed:
Example 3: Performing Arithmetic Operations
Now let’s review a simple list of integers:
myList = [22,57,15,8,29]
You can then perform various arithmetic operations, such as increasing each value in the list by 1:
myList = [22,57,15,8,29] for values in myList: print (values + 1)
You’ll now notice that each of the values in the original list increased by 1:
Example 4: Looping Across Multiple Lists
For the final case, let’s review the following two lists that contain integers:
x = [12,8,6] y = [2,3,4]
You can then multiply the values across the two lists:
x = [12,8,6] y = [2,3,4] for valuesX in x: for valuesY in y: print (valuesX * valuesY)
You’ll then get the following multiplication results:
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.