For loop#

Overview#

The for loop performs the iteration over a sequence (e.g., string, list, tuple, or range) and executes a block of code for each element in the sequence.

General syntax

for element in sequence:
    # block of code to be executed for each element

Examples#

# Example 2
for num in range(1, 5):
    print(num)
1
2
3
4
# Example 3
for x in 'Python':
    print(x)
P
y
t
h
o
n

With these simple examples, you can extrapolate for more complex interactions, such as looping over a list of image paths and open one image each time

List Comprehensions#

List comprehension is a concise way to create new lists based on existing lists or other iterable objects.

General syntax

Note

new_list = [expression for item in iterable if condition]

  • expression: The expression that defines the elements of the new list

  • item: Each item in the iterable object

  • iterable: iterable object (list, tuple, string, or range, etc)

  • condition (optional): An optional condition that filters the items from the iterable. Only items that satisfy the condition are included in the new list.

# Example of list comprehension

# From
squares = []
for x in range(1, 11):
    squares.append(x**2)

# TO
squares = [x**2 for x in range(1, 11)]

Loop Without Accessing Items#

It is not mandatory to use items of a sequence within a for loop.

sequence = ['land', 'air', 'water']

for element in sequence:
    print('Nothing change')
Nothing change
Nothing change
Nothing change