Python For Loop: Master Iteration for ML & AI

Learn the Python 'for' loop for efficient iteration over lists, strings, and dictionaries. Essential for data science, machine learning, and AI development.

2.3 Python for Loop

The for loop in Python is a powerful construct that allows you to iterate over any iterable object. This includes sequences like lists, tuples, strings, and dictionaries, as well as other iterable types. For each item within the iterable, a block of code is executed.

Basic Structure

The fundamental syntax of a for loop is as follows:

for variable in iterable:
    # Code block to be executed for each item
    # This block is indented
  • variable: This placeholder receives the value of the current item from the iterable during each pass (iteration) of the loop.
  • iterable: This is any Python object that can return its members one at a time, such as lists, strings, tuples, range() objects, dictionaries, etc.

How it Works

  1. Evaluation: The iterable is first evaluated.
  2. Initialization: The loop starts by considering the first element of the iterable.
  3. Assignment: The variable is assigned the value of the current item.
  4. Execution: The indented code block is executed.
  5. Iteration: The loop moves to the next item in the iterable, assigns it to the variable, and repeats the execution of the code block.
  6. Termination: The loop continues until all items in the iterable have been processed.

Iterating Over Different Data Types

Iterating Over Strings

Strings are sequences of characters, making them directly iterable. The for loop will process each character individually.

Example:

message = "Python"
for char in message:
    if char not in 'aeiou':  # Check if the character is not a vowel
        print(char, end='')

Output:

Pythn

Iterating Over Tuples

Tuples are immutable ordered sequences. You can easily loop through each element of a tuple.

Example:

marks = (85, 90, 78, 92)
total = 0
for mark in marks:
    total += mark
print("Total Marks:", total)

Output:

Total Marks: 345

Iterating Over Lists

Lists are mutable ordered sequences. The for loop is commonly used to process or filter data within a list.

Example:

ages = [23, 35, 42, 18, 27]
for age in ages:
    if age >= 30:
        print("Senior:", age)

Output:

Senior: 35
Senior: 42

Using range() with for Loops

The range() function is a built-in Python function that generates a sequence of numbers. It's frequently used with for loops to execute a block of code a specific number of times.

Syntax:

range(start, stop, step)
  • start (optional): The starting value of the sequence. Defaults to 0.
  • stop: The end value of the sequence. The sequence will not include this value.
  • step (optional): The increment between numbers. Defaults to 1.

Examples:

  • range(start, stop):

    for i in range(1, 6):  # Generates numbers from 1 up to (but not including) 6
        print(i, end=' ')

    Output:

    1 2 3 4 5
  • range(stop):

    for i in range(5):  # Generates numbers from 0 up to (but not including) 5
        print(i, end=' ')

    Output:

    0 1 2 3 4
  • range(start, stop, step):

    for i in range(0, 10, 2):  # Generates even numbers from 0 up to (but not including) 10
        print(i, end=' ')

    Output:

    0 2 4 6 8

Iterating Over Dictionaries

Dictionaries store data in key-value pairs. You can iterate over them in several ways:

  • Keys: By default, iterating over a dictionary iterates over its keys. You can also explicitly use the .keys() method.
  • Values: Use the .values() method to iterate over only the values.
  • Key-Value Pairs: Use the .items() method to iterate over both keys and values simultaneously.

Example – Looping through keys (default):

data = {"A": 1, "B": 2, "C": 3}
print("Iterating over keys:")
for key in data:
    print("Key:", key)

Output:

Iterating over keys:
Key: A
Key: B
Key: C

Example – Looping through keys and values using .items():

data = {"A": 1, "B": 2, "C": 3}
print("\nIterating over key-value pairs:")
for key, value in data.items():
    print(f"{key}{value}")

Output:

Iterating over key-value pairs:
A → 1
B → 2
C → 3

Example – Looping through values using .values():

data = {"A": 1, "B": 2, "C": 3}
print("\nIterating over values:")
for value in data.values():
    print("Value:", value)

Output:

Iterating over values:
Value: 1
Value: 2
Value: 3

Using else with for Loops

Python allows an optional else block to be associated with a for loop. This else block is executed only if the loop completes its entire iteration without encountering a break statement.

Example – Prime number checker:

print("Prime number check:")
for num in range(10, 20):
    for i in range(2, num):
        if num % i == 0:
            print(f"{num} is divisible by {i}")
            break  # Exit the inner loop if a divisor is found
    else:
        # This else belongs to the inner for loop
        # It executes if the inner loop completes without 'break'
        print(f"{num} is a prime number")

Output:

Prime number check:
10 is divisible by 2
11 is a prime number
12 is divisible by 2
13 is a prime number
14 is divisible by 2
15 is divisible by 3
16 is divisible by 2
17 is a prime number
18 is divisible by 2
19 is a prime number

In this example, the else block associated with the inner for i in range(2, num): loop executes if no divisors are found for num within that range, indicating num is prime.

Summary Table

Iterated TypeExample ExampleOutput Description
String'hello'Characters one by one (h, e, l, l, o)
Tuple(1, 2, 3)Each item in the tuple (1, 2, 3)
List[4, 5, 6]Each item in the list (4, 5, 6)
range()range(1, 4)Sequence of numbers (1, 2, 3)
Dictionary (keys){"a": 1, "b": 2}Keys ('a', 'b')
Dictionary (values){"a": 1, "b": 2}Values (1, 2)
Dictionary (items){"a": 1, "b": 2}Key-value pairs (('a', 1), ('b', 2))

Common SEO Keywords

  • Python for loop tutorial
  • Iterating over lists in Python
  • Python for loop with range
  • How to loop through a dictionary in Python
  • Python for loop examples
  • Python string iteration
  • Python tuple loop example
  • Python for loop with else clause
  • for loop syntax Python
  • Python key-value loop dictionary

Interview Questions

  • What is the syntax and purpose of a for loop in Python?
  • How does the Python for loop differ from loops in other languages like C or Java? (Python's for loop iterates over items of sequences, unlike C/Java's counter-based loops).
  • How can you iterate over a string using a for loop in Python?
  • How do you use the range() function in a for loop? Provide examples for different range() syntaxes.
  • What is the use of for-else in Python? Explain with a use case.
  • How do you loop through a dictionary’s keys, values, and items in Python?
  • Can you iterate over multiple sequences in one loop? How? (Yes, using zip()).
  • How do you skip specific elements in a list while looping using a for loop? (Use continue statement).
  • What happens when a for loop uses break and how does it affect the else clause? (break immediately terminates the loop, preventing the else block from executing).
  • Explain how to calculate the sum of tuple elements using a for loop in Python.