Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly. Python provides several loop mechanisms, with the for
loop being one of the most versatile. The for
loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. Here’s an in-depth look at the for
loop with various examples:
Basic for
Loop with Lists
Example:
1 2 3 |
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) |
This loop iterates through each item in the list fruits
and prints each item.
for
Loop with Strings
Example:
1 2 |
for letter in "banana": print(letter) |
This example demonstrates iterating over each character in the string “banana” and printing each character.
for
Loop with range()
The range()
function returns a sequence of numbers and is often used to execute a loop a certain number of times.
Example:
1 2 |
for i in range(5): print(i) |
This loop will print numbers 0 to 4, as range(5)
generates numbers from 0 up to (but not including) 5.
Nested for
Loops
You can nest for
loops inside each other to iterate over more complex data structures.
Example:
1 2 3 4 5 |
colors = ["red", "green", "blue"] fruits = ["apple", "banana", "cherry"] for color in colors: for fruit in fruits: print(color, fruit) |
This example prints each combination of color and fruit.
for
Loop with enumerate()
The enumerate()
function adds a counter to an iterable and returns it as an enumerate object. This can be useful for getting the index of each item in the loop.
Example:
1 2 |
for index, fruit in enumerate(fruits): print(index, fruit) |
This loop prints the index of each item in the list fruits
alongside the item itself.
for
Loop with Dictionaries
To iterate through both keys and values in a dictionary, you can use the .items()
method.
Example:
1 2 3 |
person = {"name": "John", "age": 30, "country": "Norway"} for key, value in person.items(): print(key, value) |
This loop prints each key-value pair in the person
dictionary.
for
Loop with List Comprehension
List comprehension offers a concise way to create lists. It consists of brackets containing an expression followed by a for
clause.
Example:
1 2 |
squares = [x**2 for x in range(10)] print(squares) |
This creates a list of square numbers (from 0 to 9) and prints the list.
Break and Continue
You can control the flow of your for
loops with break
and continue
.
Using break
:
1 2 3 4 |
for fruit in fruits: print(fruit) if fruit == "banana": break |
This loop will stop when “banana” is encountered.
Using continue
:
1 2 3 4 |
for fruit in fruits: if fruit == "banana": continue print(fruit) |
This loop will skip “banana” and continue with the next item.
Understanding and effectively using for
loops in Python enhances your ability to work with sequences and perform repetitive tasks efficiently. Through these examples, you can see how versatile the for
loop is for iterating over various data structures.