Python For Loop

The for Loop in Python

The for loop is used to execute a block of code multiple times by iterating over a sequence (such as a list, tuple, string, or range of numbers). It is essential for automating repetitive tasks and simplifying code.


Syntax of the for Loop

The general structure of a for loop in Python is as follows:

for variable in sequence:
    code_block
  • variable: successively takes each value from sequence.
  • sequence: a collection of elements to iterate over (list, tuple, string, etc.).
  • code_block: instructions executed in each iteration.

Example with a List

Let's iterate over a list of numbers and print each element:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

Output:

1
2
3
4
5

Using the range() Function

The range() function generates a sequence of numbers, often used with for:

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

Output:

0
1
2
3
4

range(5) generates numbers from 0 to 4 (5 excluded).

Specifying a Start and Step

for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9
  • 1: start value
  • 10: stop value (not included)
  • 2: step between values

Iterating Over a String

word = "Python"
for letter in word:
    print(letter)

Output:

P
y
t
h
o
n

Each character is treated as an element of the sequence.


Using enumerate()

enumerate() allows retrieving both the index and the value:

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index} : {fruit}")

Output:

0 : apple
1 : banana
2 : cherry

Using zip()

zip() allows iterating over multiple lists simultaneously:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

Output:

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.

The else Clause in for

A for loop can have an else clause executed after the loop if no interruption (break) occurs:

for i in range(3):
    print(i)
else:
    print("Loop completed")

Output:

0
1
2
Loop completed

If a break interrupts the loop, else does not execute.


Conclusion

  • for allows iterating over sequences such as lists, tuples, and strings.
  • range() is useful for generating number sequences.
  • enumerate() and zip() facilitate handling indices and multiple lists.
  • The else clause executes if the loop is not interrupted.

Using for effectively makes code more concise and readable.

Continue Learning

Python Variables

Popular

### Understanding Variables and Literals in Python Variables and literals are the foundation of any

Python Arguments

For You

Functions in Python let you organize your code into reusable blocks. To make functions flexible and

Python Break and Continue

For You

### The break Statement The **break** statement is used to immediately stop a loop. As soon as Pyth

Personalized Recommendations

Log in to get more relevant recommendations based on your reading history.