A for
loop is used to iterate over a list or sequence of items. In python, we can use for loop ot iterate over a list, a tuple, a dictionary, a set, or a string.
Generally, a for
loop is used to repeat a code N number of times, where N is the number of items in the sequence.
1. Syntax of for
Loop
for val in sequence: statement(s)
The variable val
represents a value from the sequence
, for the current iteration. After each iteration. the value
points to next available value in the sequence.
Once, all the values have been iterated, the for
loop terminates.
Python supports the nested for loop as well. A nested for
loop is one for
loop inside another for
loop.
for val1 in sequence: for val2 in sequence: statement(s)
2. Python for
loop examples
2.1. Iterating over list
Python program to iterate over a list of items using for
loop. This program prints all the names stored in the list.
names = ["alex", "brian", "charles"] for x in names: print(x)
Program output.
alex brian charles
2.2. Iterating over String
Python program to iterate over a string using for
loop.
In Python, strings are iterable. They are a sequence of characters.
name = "alex" for x in name: print(x)
Program output.
a l e x
2.3. Iterate through dictionary
Python program to iterate over a tuples using for
loop.
colors_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} for key in colors_dict.keys(): print(key) for item in colors_dict.items(): print(item)
Program output.
color fruit pet ('color', 'blue') ('fruit', 'apple') ('pet', 'dog')
2.4. Iterating over set
Python program to iterate over a set using for
loop.
colorSet = set(["red","green","blue"]) for color in colorSet: print(color)
Program output.
green red blue
3. The break
and continue
statements
The break
statement is used to stop the iteration, and exit the for
loop, when a certain condition is met:
names = ["alex", "brian", "charles"] print("Loop started") for x in names: print(x) if x == "brian": break; print("Loop ended")
Program output.
Loop started alex brian Loop ended
The continue
statement is used to stop the current iteration, and jump to the next iteration in the loop. It does not terminate the for
loop.
The break
statement is used to stop the iteration, and exit the for
loop, when a certain condition is met:
names = ["alex", "brian", "charles"] print("Loop started") for x in names: if x == "brian": continue; print(x) print("Loop ended")
Program output.
Loop started alex charles Loop ended
4. for
loop with else
The for
loop can have an optional else
block as well. It is called for...else
statement.
The else
block in a for...else
is executed differently depending on the present of break
statement.
- If the
break
statement NOT is present infor
loop thenelse
block is executed when all the items in the list have been iterated; and no item is left for iteration.names = ["alex", "brian", "charles"] for x in names: print(x) else: print("No name is left in the list")
Program output.
alex brian charles No name is left in the list
- If the
break
statement is present infor
loop:– The
else
block will be executed ifbreak
has not been executed because the condition forbreak
is not not met.names = ["alex", "brian", "charles"] for x in names: print(x) if x == "brian": break; else: print("No name is left in the list")
Program output.
alex brian
– The
else
block will NOT be executed ifbreak
has not been executed.names = ["alex", "brian", "charles"] for x in names: print(x) if x == "david": break; else: print("No name is left in the list")
Program output.
alex brian charles No name is left in the list
5. Looping with range() function
In Python, the for
loop can be used with range()
function as well. The range()
generates a sequence of value starting with 0, by default.
For example, range(10)
will generate numbers from 0 to 9 (10 numbers).
To generate a custom range of values, we can pass the range parameters in function range(start, stop, step_size)
.
range()
function does not eagerly load all the values in memory. It remembers the range start
, stop
, step_size
and generates the next number in the range on the go.
for i in range(5): print(i)
Program output.
0 1 2 3 4
for i in range(2, 20, 3): print(i)
Program output.
2 5 8 11 14 17
Drop me your questions related to python for loop and its examples.
Happy Learning !!