Python for loop Statement Explained

for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. The loop executes a block of code for each item in the sequence.

python for loop statement expained with examples

Syntax

for variable in iterable:
    # Code to execute for each item in the iterable

Here, variable is the name given to the variable that takes on the value of each item in the iterable, and iterable is the sequence or iterable object being iterated over.

Let’s look at some examples to understand how for loop work.

Iterating over a List

Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Iterating over a String

Example:

hello = "hello"

for char in hello:
    print(char)

Output:

h
e
l
l
o

Iterating over a Range

You can use the range() function to generate a sequence of numbers, which can then be iterated over using a for loop.

Example:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Iterating over a Dictionary

When iterating over a dictionary, the keys are returned by default. You can access the values using the values() method or the key-value pairs using the items() method.

Example:

person = {"name": "John", "age": 30, "city": "New York"}

for key in person:
    print(key)

for value in person.values():
    print(value)

for key, value in person.items():
    print(f"{key}: {value}")

Output:

name
age
city
John
30
New York
name: John
age: 30
city: New York

Using Break and Continue

You can use the break statement to exit the loop prematurely, and the continue statement to skip the current iteration and move on to the next one.

Example:

fruits = ["apple", "banana", "cherry", "date"]

for fruit in fruits:
    if fruit == "banana":
        break
    print(fruit)

for fruit in fruits:
    if fruit == "banana":
        continue
    print(fruit)

Output:

apple
cherry
date
apple
cherry
date

Using Enumerate

The enumerate() function returns an iterator that produces tuples containing the index and value of each item in the iterable.

Example:

fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Output:

0: apple
1: banana
2: cherry