Loading...

Python for loop

For Loops in Python

In Python, for loops are fundamental constructs used for iterating over sequences, including lists, tuples, dictionaries, sets, and strings. They enable you to execute a block of code multiple times, making them essential for data manipulation and automation tasks. This lesson will delve into how for loops work in Python, including key features, examples, and common use cases.

1. Basics of For Loops

A for loop allows you to traverse through a collection of items, executing the same operation for each item. This feature makes for loops powerful tools for working with data structures.

Example: Loop Through a List

python
6 lines
|
44/ 500 tokens
1
2
3
4
5
6
# Define a list of vegetables
vegetables = ["carrot", "potato", "tomato"]

# Iterate through the list and print each vegetable
for vegetable in vegetables:
    print(vegetable)
Code Tools

In this example, the loop goes through each vegetable in the list and prints its name.

2. Iterating Through Strings

Strings in Python are also iterable, which means you can use a for loop to traverse through each character.

Example: Loop Through Characters in a String

python
6 lines
|
30/ 500 tokens
1
2
3
4
5
6
# Define a string
word = "hello"

# Iterate through each character in the string
for letter in word:
    print(letter)
Code Tools

This example prints each character of the string "hello" one by one.

3. Using Break to Exit a Loop Early

You can use the break statement within a for loop to terminate the loop prematurely when a certain condition is met.

Example: Exit the Loop Based on a Condition

python
8 lines
|
52/ 500 tokens
1
2
3
4
5
6
7
8
# Define a list of fruits
fruits = ["apple", "banana", "cherry"]

# Iterate through the list and exit when encountering "banana"
for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)
Code Tools

In this scenario, the loop stops when it reaches "banana," so only "apple" is printed.

4. Skipping Items with Continue

The continue statement allows you to skip the current iteration and move to the next one in the loop.

Example: Skip an Item

python
8 lines
|
42/ 500 tokens
1
2
3
4
5
6
7
8
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Print only the even numbers
for number in numbers:
    if number % 2 != 0:
        continue
    print(number)
Code Tools

In this example, the loop skips odd numbers and only prints even ones.

5. Utilizing the range() Function

The range() function is commonly used with for loops to iterate over a sequence of numbers. It generates a series of integers based on specified parameters.

Example: Use range() in a For Loop

python
3 lines
|
14/ 500 tokens
1
2
3
# Iterate from 0 to 4
for i in range(5):
    print(i)
Code Tools

This example prints the numbers 0 through 4. You can also customize the starting point, end point, and step size.

Example: Customizing the Range

python
3 lines
|
19/ 500 tokens
1
2
3
# Iterate from 2 to 10, stepping by 2
for i in range(2, 11, 2):
    print(i)
Code Tools

Here, the loop prints every second number between 2 and 10.

6. Else Clause with For Loops

Python allows the use of an else clause with for loops, which executes a block of code after the loop finishes iterating. This block will not run if the loop is terminated with a break statement.

Example: Using Else with a For Loop

python
5 lines
|
27/ 500 tokens
1
2
3
4
5
# Iterate through a range
for i in range(3):
    print(i)
else:
    print("Loop completed successfully.")
Code Tools

In this example, "Loop completed successfully." is printed after the loop ends.

7. Nested For Loops

You can place a for loop inside another for loop, known as a nested for loop. This is useful for working with multi-dimensional data structures.

Example: Nested Loop

python
8 lines
|
57/ 500 tokens
1
2
3
4
5
6
7
8
# Define a list of colors and shapes
colors = ["red", "blue", "green"]
shapes = ["circle", "square"]

# Print every combination of colors and shapes
for color in colors:
    for shape in shapes:
        print(f"{color} {shape}")
Code Tools

This example generates combinations of colors and shapes.

8. The pass Statement

In Python, if you need a for loop that doesn’t perform any operation, you can use the pass statement. This is often used as a placeholder.

Example: Using Pass in a For Loop

python
7 lines
|
28/ 500 tokens
1
2
3
4
5
6
# Define a list
numbers = [1, 2, 3]

# Placeholder for future implementation
for number in numbers:
    pass
Code Tools

The loop does nothing here but remains syntactically correct.

Frequently Asked Questions

A for loop iterates over sequences (lists, tuples, strings, etc.), executing code for each item—ideal for automating repetitive tasks in Python programming.

For example, to print each fruit in a list: use for fruit in ["apple", "banana"]: print(fruit). This loops through the list, printing each item—key for Python loop basics.

The == operator checks if two values are equal (e.g., 5 == 5 returns True). It’s a Python comparison operator used in conditionals, not to be confused with = (assignment).

Use range(10, 0, -1) in the loop: this starts at 10, ends at 1, and decrements by 1. Perfect for reverse iteration in Python.

Still have questions?Contact our support team