Page Contents
Python For
loop
In Python, the for
loop is used to iterate over a sequence of elements. This sequence can be a list, tuple, string, dictionary, or any other iterable object. The basic syntax of a for
loop in Python is as follows:
for item in iterable: # code block to be executed for each item
Here’s a breakdown of the components:
item
: A variable that takes on the value of each element in the iterable, one at a time, during each iteration of the loop.iterable
: A collection of items to iterate.
Example 1: Looping over a List
days_list = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] print("Iterating over a List.") for day in days_list: print(day, end=" ") # Output Iterating over a List. Sun Mon Tue Wed Thur Fri Sat
Example 2: Looping over a String
message = "Hello Proedu.co!!!" print("Iterating over a String.") for char in message: print(char, end=", ") # Output Iterating over a String. H, e, l, l, o, , P, r, o, e, d, u, ., c, o, !, !, !,
Example 3: Looping over a Range
for num in range(5): print(num) # Output 0 1 2 3 4
Example 4: Using enumerate()
to Access Index and Value
days_list = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] print("Using enumerate()") for index, day in enumerate(days_list): print("Index: ", index, " Day: ", day) # Output Using enumerate() Index: 0 Day: Sun Index: 1 Day: Mon Index: 2 Day: Tue Index: 3 Day: Wed Index: 4 Day: Thur Index: 5 Day: Fri Index: 6 Day: Sat
In this example, enumerate()
is used to iterate over both the index and value of each element in the days
list. Inside the loop, index
contains the index of each element, and day
contains the value of each element.
For loop control statements
In Python, for
loops support the same loop control statements as while
loops: break
, continue
, and pass
. These statements provide flexibility and control over the flow of execution within a for
loop.
break
Statement:
The break
statement is used to exit the loop prematurely. When encountered, it causes the program to immediately exit the loop and resume execution at the next statement following the loop.
days_list = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] print("break for loop example.") for day in days_list: if day == "Wed": break # breaking loop on "Wed" print("Day: ", day) # Output break for loop example. Day: Sun Day: Mon Day: Tue
continue
Statement
The continue
statement is used to skip the rest of the code block within the loop for the current iteration, and the loop continues with the next iteration.
days_list = ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"] print("continue for loop example.") for day in days_list: if day == "Wed": continue # "Wed" is skipped here. print("Day: ", day) # Output continue for loop example. Day: Sun Day: Mon Day: Tue Day: Thur Day: Fri Day: Sat
pass
Statement
The pass
statement is a null operation; nothing happens when it executes. You can use it as a placeholder when you require a statement syntactically but you don’t want any action.
for i in range(5): if i == 2: pass # Do nothing when i equals 2 else: print(i) # output 0 1 3 4
Nested For Loops
Nested for
loops are used when you need to perform iterations within iterations. This means one or more for
loops are placed inside another for
loop. Nested for
loops are handy for tasks like working with 2D arrays, generating combinations, or traversing through multi-dimensional data structures.
Here’s a simple example of a nested for
loop:
for i in range(3): for j in range(2): print(f"({i},{j})") # output (0,0) (0,1) (1,0) (1,1) (2,0) (2,1)
In this example, we have two nested for
loops. The outer loop iterates over the values 0
, 1
, and 2
generated by range(3)
. For each iteration of the outer loop, the inner loop iterates over the values 0
and 1
generated by range(2)
. So, for each value of i
, the inner loop runs twice, generating all combinations of (i, j)
.
Nested loops can go deeper with more levels of nesting, allowing you to work with higher-dimensional data structures or perform more complex iterations. However, be cautious with deep nesting as it can make code harder to read and understand.
Here’s another example that uses nested loops to print a pattern:
for i in range(5): for j in range(i + 1): print("*", end=" ") print() # Output * * * * * * * * * * * * * * *
In this example, the outer loop controls the number of rows, and the inner loop controls the number of stars printed in each row. As the outer loop iterates from 0
to 4
, the inner loop iterates from 0
to i
, where i
is the current value of the outer loop. This creates a pattern of increasing stars in each row.
Lets take another example to print another triangle pattern.
size = 5 for i in range(size): for j in range(size - i): print("*", end=" ") print() # output * * * * * * * * * * * * * * *
Else
in for loop
In Python, you can also use the else
statement in conjunction with a for
loop. The else
block associated with a for
loop is executed when the loop completes all its iterations without encountering a break
statement. Here’s how you can use it:
for item in iterable: # code block to be executed for each item else: # code block to be executed once after the loop ends.
Here is an example
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) else: print("All fruits have been printed") # Output apple banana cherry All fruits have been printed
In this example, after iterating over all the elements in the fruits
list, the loop completes its iterations without encountering a break
statement. Therefore, the else
block is executed, printing “All fruits have been printed”.