Python for Loop in Python


for Loop in Python

A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, dictionary, or set) or any other iterable object (like range()). It allows you to execute a block of code multiple times for each item in the sequence.

The syntax of the for loop is simple, and it reads through each element of the iterable one by one.

Syntax

for variable in iterable: # Code block to execute for each item in the iterable
  • variable: The loop variable that takes on the value of each item in the iterable object.
  • iterable: The sequence (list, tuple, string, dictionary, etc.) or iterable object that you want to loop through.

How it Works

The for loop assigns the first element of the iterable to the variable and executes the code block. It continues assigning each subsequent element to the variable, repeating the code block until all elements in the iterable have been processed.


Example 1: Iterating Over a List

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Output:

apple banana cherry

Here, the for loop iterates over each item in the fruits list and prints each fruit.


Example 2: Iterating Over a String

for char in "Python": print(char)

Output:

P y t h o n

In this example, the for loop iterates over each character of the string "Python" and prints each one.


Example 3: Using range() in a for Loop

The range() function generates a sequence of numbers, which is commonly used with a for loop.

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

Output:

0 1 2 3 4

Here, range(5) generates a sequence of numbers from 0 to 4 (not including 5), and the for loop prints each number.


Example 4: Iterating Over a Dictionary

You can also iterate over the keys, values, or key-value pairs of a dictionary.

Example: Iterating Over Dictionary Keys

person = {"name": "John", "age": 30, "city": "New York"} for key in person: print(key)

Output:

name age city

Example: Iterating Over Dictionary Values

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

Output:

John 30 New York

Example: Iterating Over Dictionary Key-Value Pairs

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

Output:

name: John age: 30 city: New York

Example 5: Nested for Loop

A for loop can be nested within another for loop to iterate over multiple sequences simultaneously.

for i in range(1, 4): for j in range(1, 3): print(f"i = {i}, j = {j}")

Output:

i = 1, j = 1 i = 1, j = 2 i = 2, j = 1 i = 2, j = 2 i = 3, j = 1 i = 3, j = 2

In this example, the outer loop (for i) runs 3 times, and for each iteration, the inner loop (for j) runs twice.


Example 6: Using else with a for Loop

In Python, the for loop can have an else block, which is executed after the loop finishes iterating over all items unless the loop is terminated by a break statement.

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

Output:

0 1 2 Loop finished

If the loop runs to completion, the else block will be executed.


Example 7: Using break and continue in a for Loop

  • break: Exits the loop prematurely.
  • continue: Skips the current iteration and moves to the next.

Using break:

for i in range(5): if i == 3: break print(i)

Output:

0 1 2

In this example, the loop is terminated when i == 3.

Using continue:

for i in range(5): if i == 3: continue print(i)

Output:

0 1 2 4

Here, the iteration where i == 3 is skipped due to the continue statement.


Example 8: Iterating Over a List with enumerate()

The enumerate() function allows you to loop over a sequence while keeping track of the index of the current item.

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

Output:

0: apple 1: banana 2: cherry

Summary of for Loop in Python

  • The for loop is used to iterate over sequences like lists, tuples, strings, dictionaries, or any iterable object.
  • It processes each element one by one and executes the code block for each iteration.
  • You can use the break and continue statements to control the flow of the loop.
  • else can be used with for loops and is executed when the loop finishes without encountering a break.
  • enumerate() can be used to loop through items while also keeping track of the index.

The for loop is a fundamental control structure in Python and is widely used for iteration and processing elements in collections.