Follow AiTechWorlds on LinkedIn for professional AI content!Follow Now →
20 minLesson 5 of 34
Python Foundations

Loops: for, while, and Comprehensions

Loops: for, while, and Comprehensions

Loops are how you repeat work without repeating code. Python's loops are clean and powerful — especially list comprehensions, which let you transform data in a single expressive line.

The for Loop

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Iterate over a string
for char in "Python":
    print(char)   # P, y, t, h, o, n

# Iterate over a range
for i in range(5):
    print(i)      # 0, 1, 2, 3, 4

for i in range(2, 10, 2):  # start, stop, step
    print(i)      # 2, 4, 6, 8

enumerate() — Loop with Index

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

# Without enumerate — awkward
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# With enumerate — Pythonic
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# Start counting from 1
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. cherry

zip() — Loop Multiple Lists Together

names = ["Alice", "Bob", "Carol"]
scores = [92, 78, 85]
grades = ["A", "C+", "B"]

for name, score, grade in zip(names, scores, grades):
    print(f"{name}: {score} ({grade})")

# Output:
# Alice: 92 (A)
# Bob: 78 (C+)
# Carol: 85 (B)

Iterating Over Dictionaries

person = {"name": "Alice", "age": 30, "city": "NYC"}

# Keys (default)
for key in person:
    print(key)           # name, age, city

# Values
for value in person.values():
    print(value)         # Alice, 30, NYC

# Both — most common
for key, value in person.items():
    print(f"{key}: {value}")

The while Loop

# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1    # Don't forget to update! Infinite loop if you do.

# Wait for user input
while True:
    answer = input("Type 'quit' to exit: ")
    if answer.lower() == "quit":
        break
    print(f"You typed: {answer}")

Use for when you know how many iterations. Use while when you loop until a condition changes.

break and continue

# break — exit the loop entirely
for i in range(10):
    if i == 5:
        break
    print(i)   # 0, 1, 2, 3, 4

# continue — skip the rest of this iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)   # 1, 3, 5, 7, 9

The else Clause on Loops

A rarely known Python feature — else runs when the loop finishes without a break:

def find_user(users, target):
    for user in users:
        if user['id'] == target:
            print(f"Found: {user['name']}")
            break
    else:
        print(f"User {target} not found")  # Runs only if break never hit

users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
find_user(users, 2)   # Found: Bob
find_user(users, 99)  # User 99 not found

List Comprehensions

The most Pythonic way to create lists from other sequences:

# Traditional for loop
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension — same result, one line
squares = [x ** 2 for x in range(10)]
print(squares)   # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With a condition (filter)
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

# Transform strings
names = ["  alice  ", "  BOB  ", " carol "]
cleaned = [name.strip().title() for name in names]
print(cleaned)   # ['Alice', 'Bob', 'Carol']

# From one list to another
prices = [10.5, 8.99, 25.0, 3.49]
discounted = [round(p * 0.9, 2) for p in prices]
print(discounted)  # [9.45, 8.09, 22.5, 3.14]

Dictionary Comprehensions

# Create a dict from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)}
print(d)   # {'a': 1, 'b': 2, 'c': 3}

# Invert a dictionary
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted)   # {1: 'a', 2: 'b', 3: 'c'}

# Filter a dictionary
scores = {'Alice': 92, 'Bob': 55, 'Carol': 78, 'Dave': 45}
passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)   # {'Alice': 92, 'Carol': 78}

Set and Generator Expressions

# Set comprehension — unique values only
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {x ** 2 for x in numbers}
print(unique_squares)   # {1, 4, 9, 16}

# Generator expression — lazy evaluation (memory efficient for large data)
# Use () instead of []
total = sum(x ** 2 for x in range(1_000_000))   # Never builds a list in memory

When NOT to Use Comprehensions

Don't force comprehensions for complex logic:

# This is unreadable — use a regular loop
result = [process(transform(validate(x))) for x in data if check1(x) if check2(x) if check3(x)]

# This is readable
result = []
for x in data:
    if check1(x) and check2(x) and check3(x):
        result.append(process(transform(validate(x))))

Rule of thumb: if your comprehension needs more than one condition or a nested function call, write it as a loop.

Real-World Example: Processing Sales Data

sales = [
    {"product": "laptop", "price": 999.99, "quantity": 3},
    {"product": "mouse", "price": 29.99, "quantity": 15},
    {"product": "keyboard", "price": 79.99, "quantity": 8},
    {"product": "monitor", "price": 449.99, "quantity": 2},
]

# Total revenue per product
revenues = {s['product']: s['price'] * s['quantity'] for s in sales}

# High-value products (> $500 total revenue)
high_value = [s['product'] for s in sales if s['price'] * s['quantity'] > 500]

# Grand total
total = sum(s['price'] * s['quantity'] for s in sales)

print(revenues)    # {'laptop': 2999.97, 'mouse': 449.85, ...}
print(high_value)  # ['laptop', 'keyboard', 'monitor']
print(f"Total: ${total:,.2f}")

Next lesson: Lists — Python's most versatile data structure, explored in depth.

📱

Get this course's notes on Telegram!

Free cheat sheets, summaries & practice exercises

Get Notes Free →
!