Learn to write For Loops in Python

In [12]:
# basic syntax

for i in range(4):
    print(i)
0 1 2 3
 
For loops are a fundamental programming construct that allow you to repeat a block of code multiple times. They are especially useful when you want to perform the same operation on each item in a collection, such as a list, array, or range of numbers.

For loops work much like how a sentence sounds when you say it out loud:

> For each item (i) in a collection of items (a range of numbers from 0 to n), do some task.

For the for loop above: we have simply printed each item in a list of numbers from 0 to 4.

Lets adjust that to perform a different task. In this case, we will print the square of each number in the list.
In [13]:
for i in range(4):
    print(i ** 2)
0 1 4 9
 
Or do the calculation first and then print the result:
In [14]:
for i in range(4):
    x = i ** 2
    print(x)
0 1 4 9
 
> You can iterate over different types of collections, such as lists, tuples, and strings:
In [4]:
# list
li = ["geeks", "for", "geeks"]
for x in li:
    print(x)

# tuple   
tup = ("geeks", "for", "geeks")
for x in tup:
    print(x)

# string    
s = "abc"
for x in s:
    print(x)

# dictionary    
d = dict({'x':123, 'y':354})
for x in d:
    print("%s  %d" % (x, d[x]))

# set   
set1 = {10, 30, 20}
for x in set1:
    print(x)
geeks for geeks geeks for geeks a b c x 123 y 354 10 20 30
 

Nested For Loops



For loops can also be nested inside one another. This is useful when you want to perform operations on multi-dimensional data structures, such as matrices or grids.

In [16]:
for i in range(4):
    for j in range(5):
        print(i, j)
0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4 2 0 2 1 2 2 2 3 2 4 3 0 3 1 3 2 3 3 3 4
 

Iterating Over Multiple Collections



You can also iterate over multiple collections simultaneously using the zip() function. This is useful when you want to process corresponding elements from two or more lists together.
In [22]:
i = ["apple", "banana", "cherry"]
j = ["red", "yellow", "green"]   
      
for fruit, color in zip(i, j):
    print(f"The color of {fruit} is {color}")
The color of apple is red The color of banana is yellow The color of cherry is green
 
While the nested for loop produces unique combinations of i and j, the zip function pairs elements from two lists based on their positions.
 

We can also use the index of elements in the sequence to iterate.



The key idea is to first calculate the length of the list and then iterate over the sequence within the range of this length.
In [24]:
li = ["a", "b", "c", "d", "e"]
for index in range(len(li)):
    print(li[index])
a b c d e
 

While loop



We can use a while loop to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
In [1]:
x = 0

while (x < 6):
    x = x + 1
    print(x)
1 2 3 4 5 6
 
Be careful to avoid infinite loops, which occur when the condition never becomes false. Always ensure that the loop has a way to terminate.


Loop control statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

There are three loop control statements in Python:
1. break statement: break statement is used to exit the loop prematurely when a specified condition is met.

2. continue statement: The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is useful when we want to bypass certain conditions without terminating the loop.

3. pass statement: Does nothing and is used when a statement is syntactically required but no action is needed. This writing of empty loops is mainly useful during developement of the code structure.
In [3]:
# break statement
for i in range(10):
    if i == 5:
        break
    print(i)
0 1 2 3 4
In [16]:
# continue statement
for i in range(5):
    if i == 2: 
        continue
    print(i)
0 1 3 4
In [17]:
# pass statement
for i in range(5):
    if i == 2:
        pass
    print(i)
0 1 2 3 4
 

Aditional Notes:



* As much as for loops are powerful, they can sometimes be less efficient than using built-in functions or list comprehensions for certain tasks. Always consider the most efficient approach for your specific use case. For example, in pandas, using vectorized operations is often faster than iterating through rows with a for loop.

* AI tends to abuse for loops when simpler solutions exist. Always review and optimize code generated by AI tools.