Python is a general-purpose programming language, which emphasizes making programming easy, efficient coding, and unleashes the user’s potential. Loops are the vital part of programming as it allows the user to repetitive use a set of codes using loops. So in the following article, we will see how to use for
loops in python.
FOR Loop:
Till the iteration of the last item in the sequence, for loop run the instructions. It iterates over sets of instructions in sequence, arrays, and a tuple for a pre-defined period or until the last item and calculation are executed.
For loop can be categorized in three ways.
- Traditional for loop – It is usually used in programming language and contains three parts of a loop, i.e., initialization, condition, increment/decrement.
- Iterator/collection-based for loop – It is used for the iteration of objects and collections instead of numbers.
- Vectorize for loop – It is used to iterate parallel arrays simultaneously.
For loop in python:
As loops play an important role in programming language and make the task easy for the programmer, like other programming languages, Python also uses loops. Python allows the facility to use for loops in different sequences and segments, .i.e. for lists, strings, tuples, etc.
Syntax:
The keyword “for” is used to execute a set of conditions in for loop. The syntax for loop follows as below:
for object/item in list/tuple print(object/item)
Here are some examples of for loop in python.
For loop iteration over a list:
We can iterate through the list of numbers using for loop, and it will run once for each item in the list and print all the numbers.
1 2 3 4 5 6 | # Python for loop example to iterate over a list even_list = [2, 4, 6, 8, 10, 12, 14] for even in even_list: print(even) |
Output:
For loop for a string:
Suppose we want to iterate through a string and print each alphabet separately. In that case, we can use for loop to iterate through the string and runs every single time for each alphabet.
1 2 3 4 | # Python for loop example for a string for x in "for loop in python": print(x) |
Output:
For loop using range function:
We use the range function in python to perform a task a specific number of times. Here in the example given below, the range function calculates the sum till the first ten numbers and stores them in the sum variable.
1 2 3 4 5 6 7 | # Python for loop example with range function sum = 0 for val in range (1, 11): sum = sum + val print(sum) |
Output:
For loop to iterate over Dictionary:
As a dictionary consists of key-value pairs, we can iterate through the dictionary and get a single key-value pair using a for loop.
In the example given below, the Article type, category, and topic keys are available. You can obtain the key-value pair by writing a print statement using for loop.
1 2 3 4 5 6 | # Python for loop example to iterate over a dictionary example_dict = {'Article type':'Tutorial', 'Category':'Python Programming','Topic':'For loop in python'} for x in example_dict: print(x, ':', example_dict[x]) |
Output:
For loop with else statements:
We can use for loop with else block in python, where else would be executed when the for loop gets completed and the num is out of range.
1 2 3 4 5 6 | # Python for loop example with else statement for num in range(1, 6): print(num) else: print("Number doesn't exists") |
Output:
We can stop else statement execution by using break. The above example executes all the statements, but here, it will run only if block.
1 2 3 4 5 6 7 | # Python for loop another example with else statement for num in range(1, 6): if num == 4: break print(num) else: print("Number doesn't exists") |
Output:
Nested for loop in python:
Python also allows users to execute nested for loops. In the mentioned example, we are running two for loops inside the outer loop. The control first goes to the outer loop and prints the statement; then it will go to the next for loop to execute the print statement and then to the last loop to print both statements.
The third loop gets executed again and executes both print statements until the third loop finishes. As the third loop’s range is two, it will be executed two times, get out of the loop, and get back into the second loop. Then, the second loop’s print statement gets executed, and it will get back into the third loop once again. Thus, it will iterate till it finishes.
1 2 3 4 5 6 7 8 9 10 | # Python nested for loop example for x in range(1): print("I am outer loop " + str(x)) # Innter loop for y in range(2): print("this is first inner nested loop " + str(y)) for z in range(3): print("this is second inner nested loop " + str(z)) print("*************************************") |
Output:
For loop in python with a break statement:
The break statements are also used in For loop. The following example contains an array having a list of different items in it. In the for loop, we are iterating through each item and printing that item. We have used the if statement. In the if statement, we put a condition that if the item value is equal to the keyword, then break the loop, not iterate through the rest of the array items, and immediately get out of the loop.
1 2 3 4 5 6 7 8 | # Using break statement in Python for loop pythonforloops = ["Fedora", "Ubuntu", "Debian", "Linuxmint", "Windows", "RHEL"] for x in pythonforloops: print(x) if x == "Windows": break |
Output:
While in this example, the break statement will execute first and print values afterward.
1 2 3 4 5 6 7 8 | # Python for loop another example with the break statement pythonforloops = ["Fedora", "Ubuntu", "Debian", "Linuxmint", "Windows", "RHEL"] for x in pythonforloops: if x == "Windows": break print(x) |
Python for loop using continue statement:
We can also use for loop with continue statement. For example, you can skip the mentioned item in the if statement. The loop will continue execution until the end of the list.
1 2 3 4 5 6 7 | # Python for loop example with the continue statement pythonforloops = ["Fedora", "Ubuntu", "Debian", "Linuxmint", "Windows", "RHEL"] for x in pythonforloops: if x == "Windows": continue print(x) |
Output:
Conclusion:
This article explains for loop in python using different functions, lists, and statements. The loop is used to iterate the instructions over a specified period until the condition is right. In python, for loop is used for numerous purposes to achieve the goal. This article has explained simple ways to use for loop in python that would be beneficial for newbies.