Python Loops Cheat Sheet
Quick-reference for every loop pattern you actually use. Each section includes copy-ready snippets with inline output comments.
for Loop Basics
Python for loops iterate over any iterable: lists, strings, dicts, ranges, generators.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# apple
# banana
# cherryfor ch in 'hello':
print(ch, end=' ')
# h e l l ofor _ in range(3):
print('Hello') # prints 3 timesrange()
range(stop) produces 0 to stop-1. range(start, stop, step) gives full control. Lazy: uses nearly zero memory.
list(range(5)) # => [0, 1, 2, 3, 4]
list(range(1, 6)) # => [1, 2, 3, 4, 5]
list(range(0, 10, 2)) # => [0, 2, 4, 6, 8]list(range(5, 0, -1)) # => [5, 4, 3, 2, 1]# range(1, 10) gives 1-9. For 1-10:
list(range(1, 10 + 1)) # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]999_999 in range(1_000_000) # => True (instant, no iteration)range is lazy and supports O(1) membership testing via math, not iteration.
enumerate()
Get index + value together. Avoids manual index tracking with range(len(...)).
names = ['Alice', 'Bob', 'Carol']
for i, name in enumerate(names):
print(f'{i}: {name}')
# 0: Alice
# 1: Bob
# 2: Carolfor num, name in enumerate(names, start=1):
print(f'{num}. {name}')
# 1. Alice
# 2. Bob
# 3. Carol# Bad: manual indexing
for i in range(len(items)):
print(i, items[i])
# Good: enumerate
for i, item in enumerate(items):
print(i, item)zip()
Pair up elements from multiple iterables. Stops at the shortest by default.
names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
print(f'{name}: {score}')
# Alice: 85
# Bob: 92a = [1, 2, 3]
b = ['x', 'y']
list(zip(a, b)) # => [(1, 'x'), (2, 'y')]
# 3 is silently dropped!list(zip([1, 2, 3], ['x', 'y'], strict=True))
# ValueError: zip() argument 2 is shorter than argument 1Use strict=True when mismatched lengths indicate a bug in your data.
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, nums = zip(*pairs)
letters # => ('a', 'b', 'c')
nums # => (1, 2, 3)while Loops
Use while when the number of iterations is not known ahead of time.
count = 0
while count < 5:
print(count)
count += 1
# 0, 1, 2, 3, 4while True:
line = input('> ')
if line == 'quit':
break
print(f'You said: {line}')stack = [1, 2, 3]
while stack:
item = stack.pop()
print(item)
# 3, 2, 1break, continue, for-else
for n in range(10):
if n == 5:
break
print(n, end=' ')
# 0 1 2 3 4for n in range(6):
if n % 2 == 0:
continue
print(n, end=' ')
# 1 3 5for item in items:
if matches(item):
result = item
break
else:
result = None # no match found (no break occurred)n = 17
for i in range(2, n):
if n % i == 0:
print(f'{n} is divisible by {i}')
break
else:
print(f'{n} is prime')
# 17 is primeitertools (Standard Library)
The itertools module provides memory-efficient iterator building blocks.
from itertools import chain
list(chain([1, 2], [3, 4], [5]))
# => [1, 2, 3, 4, 5]from itertools import islice
list(islice(range(100), 5, 10))
# => [5, 6, 7, 8, 9]from itertools import cycle, islice
list(islice(cycle(['a', 'b', 'c']), 7))
# => ['a', 'b', 'c', 'a', 'b', 'c', 'a']from itertools import pairwise
list(pairwise([1, 2, 3, 4]))
# => [(1, 2), (2, 3), (3, 4)]from itertools import product
list(product('AB', '12'))
# => [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]from itertools import groupby
data = sorted(['banana', 'apple', 'blueberry', 'avocado'], key=lambda x: x[0])
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
# a ['apple', 'avocado']
# b ['banana', 'blueberry']groupby requires sorted input! It only groups consecutive matching items.
Comprehension vs Loop Performance
# List comprehension (faster: dedicated LIST_APPEND bytecode)
squares = [x**2 for x in range(1000)]
# Equivalent loop (slower: .append method lookup each iteration)
squares = []
for x in range(1000):
squares.append(x**2)Comprehensions are typically 10-30% faster for simple map/filter. Readability comes first though.
# Bad: builds entire list in memory
total = sum([x**2 for x in range(1_000_000)])
# Good: generator uses constant memory
total = sum(x**2 for x in range(1_000_000))Looping Over Dictionaries
d = {'a': 1, 'b': 2, 'c': 3}
for k in d:
print(k, end=' ')
# a b cfor v in d.values():
print(v, end=' ')
# 1 2 3for k, v in d.items():
print(f'{k}={v}', end=' ')
# a=1 b=2 c=3for i, (k, v) in enumerate(d.items()):
print(f'{i}: {k}={v}')
# 0: a=1
# 1: b=2
# 2: c=3Can you write this from memory?
Iterate over items and print each item