Advanced Loops

Python Control FlowFree Lesson

Advertisement

Advanced Loops

enumerate, zip, itertools, nested loops, and loop patterns.

Overview

Master advanced loop techniques.

enumerate

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

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

# Output:
# 0: apple
# 1: banana
# 2: cherry

# Custom start
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

# Output:
# 1. apple
# 2. banana
# 3. cherry

zip

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Paris"]

# Basic zip
for name, age in zip(names, ages):
    print(f"{name} is {age}")

# Multiple iterables
for name, age, city in zip(names, ages, cities):
    print(f"{name}, {age}, from {city}")

# With zip_longest (fills missing)
from itertools import zip_longest

list1 = [1, 2, 3]
list2 = ["a", "b"]

for item in zip_longest(list1, list2, fillvalue="N/A"):
    print(item)
# (1, 'a')
# (2, 'b')
# (3, 'N/A')

itertools

import itertools

# chain - flatten iterables
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(itertools.chain(list1, list2))
print(combined)  # [1, 2, 3, 4, 5, 6]

# product - Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
for combo in itertools.product(colors, sizes):
    print(combo)
# ('red', 'S')
# ('red', 'M')
# ('red', 'L')
# ('blue', 'S')
# ('blue', 'M')
# ('blue', 'L')

# combinations - choose r from n
items = ["A", "B", "C", "D"]
for combo in itertools.combinations(items, 2):
    print(combo)
# ('A', 'B')
# ('A', 'C')
# ('A', 'D')
# ('B', 'C')
# ('B', 'D')
# ('C', 'D')

# permutations - ordered arrangements
for perm in itertools.permutations(items, 2):
    print(perm)

# groupby
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4)]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
    print(f"{key}: {list(group)}")
# A: [('A', 1), ('A', 2)]
# B: [('B', 3), ('B', 4)]

# cycle - infinite cycle
colors = ["red", "green", "blue"]
color_cycle = itertools.cycle(colors)
for i in range(6):
    print(next(color_cycle), end=" ")
# red green blue red green blue

# islice - slice iterator
for item in itertools.islice(range(10), 3, 7):
    print(item, end=" ")
# 3 4 5 6

Loop Patterns

# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6]

# Chunk list
def chunk(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i:i + size]

print(list(chunk(range(10), 3)))
# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

# Sliding window
def sliding_window(lst, size):
    for i in range(len(lst) - size + 1):
        yield lst[i:i + size]

print(list(sliding_window([1, 2, 3, 4, 5], 3)))
# [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Practice

Implement a function that finds all pairs in a list that sum to a target.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement