Python For Loops
About Python For Loop
In Python, the 'for' loop is used to iterate over a sequence or any iterable object such as a list, tuple, string, or range.
It repeatedly executes a block of code for each element in the sequence until the iteration of the sequence is completed.
When the iterator is exhausted, the loop terminates.
If there is 'else' clause, it will be executed, when the iterator is exhausted.
Syntax of 'for' loop
for: The for loops begins with the keyword 'for'.
item_variable: 'for' keyword is followed by a variable named 'item_variable' that represents the element/item of the sequence being iterated over. You can choose a variable name. 'in' is another keyword that shows relation between variable and sequence.
sequence: 'sequence' is the iterable object (e.g., a list, tuple, string, range, or any other iterable) over which the loop iterates. You need to replace it with your iterable object.
The sequence is followed by a colon (:) which is part of the syntax.
'for' loop to iterate a list
In the following example, 'for' loop is used to iterate over a list of fruit names:
Example of 'for' loop to iterate a list
Output of the above example
Apple
Banana
Orange
Watermelon
Explanation of example:
fruit_list = ["Apple", "Banana", "Orange", "Watermelon"] is a list of string of fruit names.
for fruit in fruit_list: defines the 'for' loop where item is the variable and 'fruit_list' is the list sequence.
print(fruit) is the code block under for loop which prints each element of fruit list.
'for' loop to iterate a tuple
In the following example, 'for' loop is used to iterate over a tuple of numbers:
Example of 'for' loop to iterate a tuple
Output of the above example
1
2
3
4
Explanation of example:
num_tuple = (1, 2, 3, 4) is a tuple of numbers.
for number in num_tuple: defines the 'for' loop where 'number' is the variable and 'num_tuple' is the tuple sequence.
print(number) is the code block under for loop which prints each element of 'num_tuple' tuple.
'for' loop to iterate a set
In the following example, 'for' loop is used to iterate over a set of numbers:
Example of 'for' loop to iterate a set
Output of the above example
1
2
3
4
Explanation of example:
num_set = {1, 2, 3, 4} is a set of numbers.
for numberItem in num_set: defines the 'for' loop where 'numberItem' is the variable and 'num_set' is the set sequence.
print(numberItem) is the code block under for loop which prints each element of 'num_set' set.
'for' loop to iterate a string
In the following example, 'for' loop is used to iterate over a string:
Example of 'for' loop to iterate a string
Output of the above example
P
y
t
h
o
n
Explanation of example:
var_String = "Python": This line declares a string variable named 'var_String' and assigns value "Python" to the variable.
for letter in var_String: defines the 'for' loop where 'letter' is the variable and 'var_String' is the string sequence.
print(letter) is the code block under 'for' loop which prints each element of 'var_String' string.
'for' loop to iterate over range function
In the following example, 'for' loop is used to iterate over a range function:
Output of the above example
0
1
2
3
4
5
Explanation of example:
for num in range(6): defines the 'for' loop where 'num' is the variable and 'range(6)' is the range() function. The range(6) function generates a sequence of 6 numbers starting from 0 up to 5.
print(num) is the code block under 'for' loop which prints each value of num generated by the range(6) function.
'for' loop to iterate over a dictionary
The 'for' loop cab be used to iterate through the keys and values of the dictionary In the following example, 'for' loop is used to iterate over a dictionary:
Example of 'for' loop to iterate a dictionary
Output of the above example
0
1
2
3
4
5
Explanation of examples:
Dictionary key example:
personDict = {"name": "John", "age": 25, "country": "UK"}: This line defines a dictionary named 'personDict'.
for key in personDict: defines a 'for' loop where 'key' is the variable that refers to each key of the 'personDict' dictionary.
print(key) is the code block under the 'for' loop that prints each key of the 'personDict' dictionary.
Dictionary value example:
for value in personDict.values(): defines another 'for' loop where 'key' is the variable that refers to each value of the 'personDict' dictionary. 'personDict.values()' defines the values of the dictionary.
print(value) is the code block under the 'for' loop that prints each value of the 'personDict' dictionary.
Dictionary key & value example:
for key, value in personDict.items(): defines yet another 'for' loop where 'key' and 'value' are the variables that refer to each key and value of items of the 'personDict' dictionary. 'personDict.items())' defines the items of the dictionary.
print(key, ":", value) is the code block under the 'for' loop that prints each key and value of the 'personDict' dictionary.
'for' loop with 'else' block
In Python, 'for' loop takes an 'else' block.
The code inside the 'else' block runs once when the iteration of the sequence is completed.
Example of 'for' loop with 'else' block
Output of the above example
Apple
Banana
Orange
For loop finished & else block runs.
Explanation of example:
fruit_list = ["Apple", "Banana", "Orange"]: This line defines a list.
for fruit in fruit_list: defines a 'for' loop where 'fruit' is the variable representing the item of 'fruit_list' list.
print(fruit) is the code block under the 'for' loop that prints each item of the 'fruit_list' list.
else: The 'else' block runs once the iteration of the 'for' loop is completed.
print("For loop finished & else block runs.") It prints the message when the 'else' block runs.
'for' loop with nested loops
In Python, 'for' loop can have nested loops (loop within a loop).
The nested for loops are used to iterate over multiple sequences as demonstrated in the following example:
Example of nested 'for' loop
Output of the above example
Green
Red
Apple
Banana
Explanation of example:
fruitcolor_list = [["Green", "Red"],["Apple", "Banana"]]: This line defines a list with two elements of lists - ["Green", "Red"] and ["Apple", "Banana"].
for itemlist in fruitcolor_list: defines a 'for' loop where 'itemlist' is the variable representing the list item of 'fruitcolor_list' list.
for item in itemlist: defines a nested 'for' loop where 'item' is the variable representing the each element of each 'itemlist' list.
print(item) is the code block under the nested 'for' loop which prints each value of the 'itemlist' list.
'for' loop with 'break' and 'continue'
In Python, 'break' is used to terminate (stop) the 'for' early at some point.
'continue' is used to skip the current iteration and moves to the next one.
'break' and 'continue' are used with for loop as demonstrated in the following examples:
Example of 'break' with 'for' loop
Output of the above example
0
1
2
The number was 3 and the loop exited.
Explanation of example:
for num in range(11): defines a 'for' loop where 'num' is the variable representing the number of range() function.
if num == 3: checks if the num value is equal to 3.
print("The number was {} and the loop exited.".format(num)) prints the message if the num value is equal to 3.
break exits the 'for' loop when the 'num' is equal to 3.
print(num) prints the num value as long as the num value is less than 3.
Example of 'continue' with 'for' loop
Output of the above example
1
3
5
7
9
Explanation of example:
for number in range(10): defines a 'for' loop where 'number' is the variable representing the number of range() function.
if number % 2 == 0: checks if the number is an even number.
continue skips the current iteration if the number is even and moves to the next one.
print(number) prints the number value if the number is not even.
You can find even numbers by skipping the odd numbers in the same way.
'for' loop with index using enumerate() function
The enumerate() function adds a counter (an index) to an iterable and returns it as an enumerate object, which can then be used directly in 'for' loop. The counter can be used as the index of each element of a sequence like list as demonstrated in the following example:
Output of the above example
0 John
1 Jenny
2 Milton
Explanation of example:
personList = ['John', 'Jenny', 'Milton']: This line defines a list with person names.
for index, person in enumerate(personList):: Here enumerate() function takes 'personLis' as parameter. 'index' takes the current index and 'person' takes the value of current element of 'personList'.
print(index, person) is the code block under 'for' loop which prints the current index and person name of the 'personList'.
'for' loop with list comprehension
List comprehension provides a concise way to create a list using 'for' loop as demonstrated in the following example:
Output of the above example
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Explanation of example:
squares = [x**2 for x in range(10)]: This line defines a list comprehension where the expression 'x**2' is used to create square of each number of the 'range(10)' (from 0 to 9). Expression is placed before the 'for' loop. Finally, it creates a list with the squares of each number of the range.
print(squares) prints a new list of squared numbers.
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor by creating more 'for' loop with different sequences. Create more Python for loop in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.
Python Editor