In Python, a for loop is used to iterate over a sequence (such as a list, tuple, dictionary, or string) or any other iterable object. Here's the basic syntax of a for loop in Python:
for item in iterable:
# Do something with item
Where:
-
item
is a variable that takes the value of each item in the iterable object during each iteration of the loop. -
iterable
is the sequence or iterable object you want to loop through.
Here's a simple example demonstrating the usage of a for
loop:
# Iterating over a list
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)
# Iterating over a string
my_string = "hello"
for char in my_string:
print(char)
# Iterating over a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(key, value)
# Using range() function
for i in range(5):
print(i)
In the last example, range(5) generates a sequence of numbers from 0 to 4 (exclusive) which the loop iterates over.
You can also use break and continue
statements within a for
loop to control its flow, similar to other programming languages. This allows you to exit the loop prematurely or skip certain iterations based on specific conditions.
You can have loops within loops, known as nested loops, to perform more complex iterations.
for i in range(3):
for j in range(2):
print(i, j)
List Comprehensions:
List comprehensions provide a concise way to create lists. They can include loops and conditions.
# Create a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
Enumerate:
enumerate()
function can be used to iterate over both the indices and elements of a sequence.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
Using else with Loops:
You can include an else
block that executes when the loop completes normally (without encountering a break
statement).
for i in range(5):
print(i)
else:
print("Loop completed without encountering a break statement.")
Loop Control Statements:
break and continue
statements can be used to control the flow of loops.
for i in range(10):
if i == 3:
continue # Skip iteration if i is 3
if i == 8:
break # Exit loop if i is 8
print(i)
Using zip():
zip()
function combines elements from multiple sequences.
names = ['Alice', 'Bob', 'Charlie']
ages = [30, 25, 35]
for name, age in zip(names, ages):
print(name, age)
Using reversed():
reversed()
function reverses the order of elements in a sequence.
for i in reversed(range(5)):
print(i)
These are just a few examples of how you can use loops effectively in Python. Experimenting with different combinations and understanding their behavior will help you become proficient in using loops to solve various problems.