What is the for loop in Python
The for loop in Python is a built-in construct for iterating over elements of collections (lists, strings, tuples, sets, and dictionaries) or for performing operations on sequences of numbers. The for loop is one of the most important tools in Python and allows efficient data processing.
The basic structure of the for loop
for element in collection:
# A block of code that is executed for each element
Examples of using the for loop
Iterating through the list
One of the most common ways to use the for loop is to bypass the list elements.:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Iterating over the line
The for loop allows you to iterate through each character in a string:
message = "Hello, World!"
for char in message:
print(char)
Dictionary iteration
When working with dictionaries, you can iterate through keys, values, or key-value pairs.:
person = {'name': 'Ivan', 'age': 30, 'city': 'Moscow'}
# Key iteration
for key in person.keys():
print(key)
# Iterate over the values
for value in person.values():
print(value)
# Key-value pair iteration
for key, value in person.items():
print(f"{key}: {value}")
Iterating over a tuple
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
The range() function in the for loop
The range() function is used to generate sequences of numbers, which makes it indispensable for iteration in the for loop.
The main use cases for range()
# Iteration over a sequence of numbers from 0 to 4
for i in range(5):
print(i) # outputs: 0, 1, 2, 3, 4
# Iteration with initial value and final value
for i in range(2, 8):
print(i) # outputs: 2, 3, 4, 5, 6, 7
# Iterate in steps
for i in range(1, 10, 2):
print(i) # outputs: 1, 3, 5, 7, 9
Increment and decrement in Python
What is an increment and a decrement
An increment is an increase in the value of a variable by a certain number, usually by 1. A decrement is a decrease in the value of a variable by a certain number, usually by 1.
Increment in Python
In Python, there is no special operator for increment (like ++ in C++ or Java), but the += operator is used:
# Initialize the variable
number = 5
# Increasing the value of a variable by 1
number += 1
print(number) # will output 6
Explanation:
number = 5sets the initial value of the number variable to 5the number += 1means "increase the value of the number by 1". This is equivalent to writingnumber = number + 1print(number)outputs the new value of the number variable, which is now 6
Decrement in Python
Python uses the -= operator for decrement:
# Initialize the variable
number = 5
# Reducing the value of a variable by 1
number -= 1
print(number) # will output 4
Explanation:
number = 5sets the initial value of the number variable to 5the number -= 1means "reduce the value of the number by 1". This is equivalent to writingnumber = number - 1print(number)outputs the new value of the number variable, which is now 4
Assignment operators with other mathematical operations
Increment and decrement work with all mathematical operations. Instead of a number, you can use another variable:
a = 5
a += 5 # a = 10 (addition)
a -= 3 # a = 7 (subtraction)
a *= 4 # a = 28 (multiplication)
a /= 2 # a = 14.0 (division)
a //= 3 # a = 4.0 (integer division)
a %= 5 # a = 4.0 (remainder of division)
a **= 2 # a = 16.0 (exponentiation)
Cycle control: break, continue and else
The break operator
The break operator is used to exit the loop early.:
for i in range(10):
if i == 5:
break
print(i)
# Outputs: 0, 1, 2, 3, 4
The continue operator
The continue operator is used to skip to the next iteration of the loop, skipping the remaining code in the current iteration.:
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Outputs: 1, 3, 5, 7, 9
The else block in the for loop
The for loop may have a else block, which is executed if the loop ended without using the break operator:
for i in range(5):
print(i)
else:
print("The loop is completed without interruptions")
Nested for loops
You can use one for loop inside another 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() # line break
The enumerate() function
The enumerate() function allows you to get the index of an element during iteration:
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Practical tips for using the for loop
- Use clear variable names for iteration
- Use list comprehensions for simple operations on lists
- Use enumerate() when you need an element index
- Keep performance in mind when working with large amounts of data
The for loop is a powerful Python tool that allows you to efficiently process data and perform repetitive operations. Mastering all its features will help you write more readable and efficient code.