Python for Loop

Understand the power of Python for loop. Learn how to iterate over lists, strings, dictionaries, and more with clear explanations and examples.

Python-for-Loop-Featured
Table of Contents

What is a for loop in Python?

Python for loop is a control structure that lets you repeat a block of code a set number of times. It’s great for working with lists or other collections of things. Here’s the basic syntax:

Python for Loop Syntax

Python for Loop
for item in some_list:
    # Code to be repeated for each 'item'

Explanation

  • Line 1: This tells Python to take each item from your some_list (like a list of numbers or names) and assign it to a variable called item on each loop.
  • Line 2: This indented part is the code that will run on each loop, using the current value of item.

Python for Loop Example 1

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print("I like to eat", fruit)

Explanation

  • Line 1: Creates a list called fruits to hold our fruit names.
  • Line 2:  Starts the loop, taking each item from fruits and calling it fruit.
  • Line 3: Prints a message for each fruit in our list.

Output 1

I like to eat apple
I like to eat banana
I like to eat orange

Example 2

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

Explanation

  • Line 1: Creates a list called numbers.
  • Line 2: Begins the loop, assigning each value in numbers to the variable number.
  • Line 3: For each number in the list, this line multiplies it by 2 and prints the result.

Output 2

2
4
6
8
10


Understanding Python for Loop Execution

Here’s how a for loop in Python executes step-by-step:

Syntax

for item in something_to_loop_over:
    # Code to execute on each item
  1. Initialization: The loop starts by taking the first item from the thing you’re iterating over (something_to_loop_over, like a list or string).
  2. Body Execution: The code inside the loop’s indented block is run once using the current item.
  3. Iteration: The loop goes back and takes the next item from what you’re looping over.
  4. Repeat: Steps 2 and 3 repeat for each remaining item.
  5. Completion: When there are no more items left, the loop finishes.

Using else with Python for Loops

In Python, you can add an else clause to a for loop. This else part runs after the loop finishes only if the loop ended normally (meaning it didn’t hit a break statement). Here’s the syntax:

Syntax

for item in something_to_loop_over:
    # Code to execute on each item
else:
    # Code to run if loop finished without 'break'

The else part only runs if the loop goes through all iterations without a break interrupting it.

Example

names = ["Alice", "Bob", "Eve"]
search_name = "David"

for name in names:
    if name == search_name:
        print(search_name, "found!")
        break # Exit loop if name is found
else:
    print(search_name, "not found")

Explanation

  • Line 1: Creates our list of names.
  • Line 2 : The name we want to find.
  • Line 4: Begins the loop over our names list.
  • Line 5: Checks each name to see if it matches.
  • Line 8: Executes if David was not found in the list.

Output

David not found


Controlling Flow with break in Python for Loops

A break statement inside a for loop lets you immediately stop the loop, even if it hasn’t finished going through all the items. Here’s the basic syntax:

Syntax

for item in something_to_loop_over:
    # Code to execute on each item
    if some_condition_is_met:
        break  # Stop the loop here

If a certain condition becomes true, the break keyword immediately ends the loop, skipping any remaining items.

Example

numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
    if number % 2 == 0:  # Check if number is even
        print(number, "is even")
        break  # Stop as soon as an even number is found

Explanation

  • Line 1: Creates our list of numbers.
  • Line 2: Starts looping through the list.
  • Line 3: Checks if the current number is divisible by 2 (even).
  • Line 5: If an even number is found, exits the loop.

Output

2 is even


The continue Statement in Python for Loops

The continue statement in a for loop lets you skip the rest of the current iteration and jump to the next one. This is useful when you want to do something for most items in a list but must ignore certain ones based on a condition. Here’s the syntax:

Syntax

for item in something_to_loop_over:
    # Code to execute on each item
    if some_condition_to_skip:
        continue  # Skip to the next item

If a certain condition is met, continue skips the rest of the code in that iteration and goes to the next item in the loop.

Example

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:  # Skip even numbers
        continue
    print(number)  # Print only odd numbers

Explanation

  • Line 1: Creates our numbers list.
  • Line 2 Starts the loop.
  • Line 3: continue: If the current number is even, skip to the next one.
  • Line 5: Only reached if the number is odd.

Output

1
3
5


The pass Statement in Python for Loops

The pass statement in Python is essentially a placeholder. Inside a for loop, it means “do nothing for this iteration.” This is often used when you know you need a loop but are not ready to fill in the actual code yet. Here’s the syntax:

Syntax

for item in something_to_loop_over:
    # Placeholder for where code will go
    pass 

The pass tells Python to do nothing and just move to the next item in the loop.

Example

cities = ["London", "Paris", "Tokyo"]
for city in cities:
    # Let's pretend we'll write code to process city data later
    pass

Explanation

  • Line 1: Creates a list of cities.
  • Line 2: Begins looping through the cities.
  • line 4: A placeholder indicating we intend to add code to work with each city later. For now, the loop just iterates without doing anything.

Iterating with the range() Function in Python for Loops

The range() function is a super helpful partner to for loops in Python. It generates a sequence of numbers to control how many times your loop runs. Here’s the basic syntax:

Syntax

for variable in range(stop): 
    # Code to run for each number generated

Line 1: Sets up the loop. variable will take on each number the range() function creates.

range() Variations

  • range(stop): Starts at 0, goes up to (but not including) stop.
  • range(start, stop): Starts at start, goes up to (but not including) stop.
  • range(start, stop, step): Starts at start, goes up to stop (not including it), and increments by the step value.

Example 1

for i in range(1, 6):  # Print numbers 1 to 5
    print(i * 2)  

Explanation

  • Line 1: The loop will run 5 times; i will be 1, then 2, and so on, up to 5.
  • Line 2: For each value of i, this line multiplies it by 2 and prints the result.

Output

2
4
6
8
10

The range() function in Python offers flexibility in how you create number sequences for loops. Here’s a breakdown of the different ways to use it:

1. range(stop)

for i in range(5): # Generates 0, 1, 2, 3, 4

Generates numbers starting from 0 up to (but not including) the stop value.

2. range(start, stop)

for i in range(2, 7): # Generates 2, 3, 4, 5, 6 

Starts at the start number and goes up to (but not including) the stop value.

3. range(start, stop, step)

for i in range(1, 10, 2): # Generates 1, 3, 5, 7, 9

Starts at the start value, goes up to (but not including) stop, and increments by the step value.

Example 2

for i in range(5, 0, -1):  # Countdown from 5 to 1
    print(i)

Explanation

  • Line 1: i takes values 5, 4, 3, 2, 1.
  • Line 2: Prints the current value of i on each loop iteration.

Output

5
4
3
2
1


Structuring Nested for Loops in Python

Nested for loops mean putting a for loop inside another for loop. This is great when you need to work with combinations of things, like rows and columns in a table. Here’s the basic syntax:

Syntax

for item_outer in outer_list:
    for item_inner in inner_list:
        # Code to run for each combination
  • Line 1: The outer loop, item_outer takes values from the outer_list.
  • Line 2: For each item_outer, the inner loop runs, with item_inner taking values from the inner_list.

Example

for x in range(1, 4):  # Rows
    for y in range(3):  # Columns
        print("*", end=" ")
    print() # Go to a new line after each row

Explanation

  • Line 1: Outer loop represents rows (runs 3 times).
  • Line 2: Inner loop represents columns (runs 3 times for each row)
  • Line 3: Prints a star with a space for each column.
  • Line 4: Moves to a new line after each complete row.

Output

***
***
***


Handling Potential Infinite for Loops

In Python, you can make an infinite for loop using the while keyword with a condition that’s always True. This means the loop will keep running forever (well, until your program is stopped or runs out of resources). Here’s the example:

Example

while True:
    print("This loop will run forever!")

Explanation

  • Line 1: Starts the infinite loop.
  • Line 2: Prints a message repeatedly, demonstrating the never-ending nature of the loop.

Note: Use infinite loops carefully! They’re usually best with a break statement inside to stop the loop when a condition is met; otherwise, your program might run forever.


Iterating Through Dictionaries with Python for Loops

Python lets you loop through dictionaries, but there are a few ways to do it, depending on whether you want the keys, values, or both. Here’s the basic syntax for getting the keys:

Syntax

for key in my_dictionary: 
    # Code to do something with 'key'

Line 1: This says to take each key from my_dictionary and loop.

Example

fruits = {"apple": "red", "banana": "yellow"}
for fruit in fruits:
    print("Fruit:", fruit)  

Explanation

  • Line 1: Creates our dictionary of fruits.
  • Line 2: Starts the loop, assigning each key in fruits to the variable fruit.
  • Line 3: For each fruit (key), prints the fruit name.

Output

Fruit: apple
Fruit: banana

Looping through keys

Python lets you loop through a dictionary’s keys directly. This is useful if you only need to work with the keys themselves. Here’s the basic structure:

Syntax

for key in my_dictionary: 
    # Code to do something with 'key'

Line 1: Iterates through each key in the dictionary.

Example

capitals = {"France": "Paris", "Germany": "Berlin"}
for country in capitals:
    print("The capital of", country, "is", capitals[country])

Explanation

  • Line 1: Creates a dictionary called capitals storing country-capital pairs.
  • Line 2: The loop starts, assigning each key (country name) to the variable country.
  • Line 3: Prints a message where country is the key, and capitals[country] accesses the corresponding capital city using the key.

Output

The capital of France is Paris
The capital of Germany is Berlin

Looping through values

Here’s how you loop through the values of a dictionary in Python:

Syntax

for value in my_dictionary.values(): 
    # Code to do something with 'value'

Line 1: Iterates through each value in the dictionary.

Example

colors = {"car": "red", "sky": "blue"}
for color in colors.values():
    print("I see something", color)

Explanation

  • Line 1: Creates a dictionary called colors where values represent colors of different objects.
  • Line 2: The loop iterates specifically over the color values (red, blue).
  • Line 3: Prints a message for each color found in the colors dictionary.

Output

I see something red
I see something blue

Looping through key-value pairs (items)

Python’s items() method makes it easy to loop through both keys and values of a dictionary at the same time. Here’s the syntax:

Syntax

for key, value in my_dictionary.items(): 
    # Code to do something with 'key' and 'value'

Line 1: Iterates through key-value pairs as tuples.

Example

phonebook = {"Alice": "123-4567", "Bob": "987-6543"}
for name, number in phonebook.items():
    print(name, ":", number)

Explanation

  • Line 1: Creates a dictionary called phonebook to store names and phone numbers.
  • Line 2: The loop gets each (name, number) pair from the phonebook.
  • Line 3: Prints each person’s name followed by their corresponding phone number.

Output

Alice : 123-4567
Bob : 987-6543


Iterating Through Lists with Python for Loops

Python makes it super easy to loop through lists. Here’s the basic syntax:

Syntax

for item in my_list:
    # Code to run for each item

Line 1: The loop takes each item from your my_list and assigns it to the item variable in each go-around.

Example

colors = ["red", "green", "blue"]
for color in colors:
    print("I like the color", color)

Explanation

  • Line 1: Creates a list called colors.
  • Line 2: Starts the loop, assigning each color from the list to the color variable.
  • Line 3: Prints a message for each color in the list.

Output

I like the color red
I like the color green
I like the color blue


Iterating Through Tuples with Python for Loops

Just like lists, Python lets you loop through tuples as well. Here’s the basic syntax:

Syntax

for item in my_tuple:
    # Code to run for each item

Line 1: This starts the loop, taking each item from your my_tuple and assigning it to a variable called item on each iteration.

Example

coordinates = (10, 20, 30)
for coordinate in coordinates:
    print("Coordinate:", coordinate)

Explanation

  • Line 1: Creates a tuple called coordinates to store a set of coordinates.
  • Line 2: The loop iterates over each value in the coordinates tuple.
  • Line 3: Prints each coordinate value from the tuple.

Output

Coordinate: 10
Coordinate: 20
Coordinate: 30


Iterating Through Strings with Python for Loops

In Python, you can loop through the individual characters of a string using a for loop. Here’s the syntax for doing so:

Syntax

for character in my_string:
    # Code to run for each character

Line 1: This tells Python to take each character from your my_string in turn.

Example

sentence = "Hello there!"
for char in sentence:
    print(char)

Explanation

  • Line 1: Creates a string called sentence.
  • Line 2: The loop iterates over each char (character) in the sentence.
  • Line 3: Prints each character of the sentence on a separate line.

Output

H
e
l
l
o

t
h
e
r
e
!