For loop in Python is used for sequential traversal. It can iterate over the elements of any sequence, such as a list. Loop continues until we reach the last element in the sequence.
Python for loop
Python for loop is used to iterate over the sequence either the list, a tuple, a dictionary, a set, or the string. Python for loop starts with a keyword “for” followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through.
The body of for loop is separated from the rest of the code using indentation. The for loops are traditionally used when you have a block of code in which you want to repeat a fixed number of times.
Syntax
The general syntax looks like the following code.
for <variable> in <sequence>: <statements>
Let us take a simple example of For Loop in Python.
# app.py GoT = ['Daenerys', 'Jon', 'Tyrion'] for item in GoT: print(item)
See the output.
In the above example, we have taken one list and iterated the list in the loop, and printed the item one by one.
Looping Through a String in Python
The strings are iterable objects; they contain the sequence of characters. Let us take the following example.
# app.py name = 'KRUNAL' for item in name: print(item)
See the output.
The break Statement in Python
Using a break statement in the loop, we can stop it before it has looped through all the elements. See the below example.
# app.py GoT1 = ['Daenerys', 'Jon', 'Tyrion'] for item1 in GoT1: print(item1) if item1 == 'Jon': break
In the above example, if the current iterable item equals Jon, it will break the loop. That is why we will not see the Tyrion logged in the console.
Else in For Loop
The else keyword in the for loop specifies the code block to be executed when a loop is finished.
If the else statement is used with the for loop, the else statement is performed when the loop has exhausted iterating the list.
# app.py for x in range(5): print(x) else: print('Executed Else Statement!!')
Output
Python range() Function
The range() function returns the sequence of numbers, starting from 0 by default, increasing by 1 by default, and ending at the specified number. We can generate the sequence of numbers using the range() function.
# app.py for z in range(4): print(z)
Output
Python continue Statement
With the help of the continue statement, we can stop the current iteration of the loop and continue with the next iteration.
# app.py GoT2 = ['Daenerys', 'Jon', 'Tyrion'] for item2 in GoT2: if item2 == 'Jon': continue print(item2)
In the above example, when the current iterator is Jon, it will end the iteration and does not print the Jon in the console.
Output
Nested For loops in Python
The nested loop is a loop inside a loop. The “inner loop” will be executed once for each iteration of the “outer loop.” See the below demo.
# app.py for x in color: for y in fruits: print(x, y)
Output
That’s it for this tutorial.