The for loop in Python: a complete guide with examples
The for loop in Python is a powerful tool for iterating over sequences and iterable objects. Unlike other programming languages, where the for loop is often used to perform a certain number of repetitions, Python's for loop is more flexible and allows you to iterate through the elements of a collection directly.
Syntax of the for loop
The basic structure of the for loop is as follows:
for element in sequence:
# A block of code executed for each element
Where:
elementis a variable that takes the value of each element of the sequence in turnsequence- any iterable object (list, string, tuple, range, dictionary, set)
Iterating through the list
The most common use case is iterating over list items:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Result:
apple
banana
cherry
Line iteration
The for loop on the string allows you to process each character separately:
word = "hello"
for letter in word:
print(letter)
Result:
h
e
l
l
0
Using the range() function
For iteration over numbers, the range() function is used:
for i in range(5):
print(i)
The result:
0
1
2
3
4
Parameters of the range() function
The range() function can take up to three arguments:
range(stop)- from 0 to stop (not including stop)range(start, stop)- from start to stop (not including stop)range(start, stop, step)- from start to stop in increments of step
for i in range(1, 10, 2):
print(i)
Result:
1
3
5
7
9
Nested loops for
Nested loops are used to work with multidimensional data structures:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=' ')
print()
Result:
1 2 3
4 5 6
7 8 9
The enumerate() function
Enumerate in Python allows you to get the index and value of an element at the same time:
names = ['Alexey', 'Boris', 'Vera']
for index, name in enumerate(names):
print(f' Index: {index}, Name: {name}')
Result:
Index: 0, Name: Alexey
Index: 1, Name: Boris
Index: 2, Name: Vera
Initial index value
You can set the initial value for the index:
for index, name in enumerate(names, start=1):
print(f'№{index}: {name}')
for loop with else
A special feature of Python is the else block after the for loop. It is executed only if the cycle ended naturally (the break was not interrupted):
for i in range(5):
print(i)
else:
print("The loop is completed without interruption")
If the cycle is interrupted:
for i in range(5):
if i == 3:
break
print(i)
else:
print("This text will not be displayed")
Dictionary iteration
The for loop in the dictionary can be executed in several ways:
student = {'name': 'Ivan', 'age': 25, 'city': 'Moscow'}
# By keys
for key in student:
print(key)
# By values
for value in student.values():
print(value)
# By key-value pairs
for key, value in student.items():
print(f'{key}: {value}')
Cycle management
The break operator
Interrupts the execution of the loop:
for i in range(10):
if i == 5:
break
print(i)
The continue operator
Skips the current iteration and moves on to the next one.:
for i in range(5):
if i == 2:
continue
print(i)
List Comprehensions
An alternative to the for loop for creating lists:
# Regular
squares loop = []
for i in range(5):
squares.append(i**2)
# List inclusion
squares = [i**2 for i in range(5)]
Practical examples
Counting elements
numbers = [1, 2, 3, 2, 1, 2]
count = 0
for num in numbers:
if num == 2:
count += 1
print(f'Number of twos: {count}')
Sum of elements
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f' Sum: {total}')
Finding the maximum element
numbers = [45, 12, 78, 23, 56]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(f' Maximum number: {max_num}')
Conclusion
The for loop in Python is a universal tool for iterating over any sequence. It ensures code readability and execution efficiency. Understanding all the features of the for loop will help you write more elegant and productive Python code.