Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. Python
  4. Python Loops Cheat Sheet
PythonCheat Sheet

Python Loops Cheat Sheet

Quick-reference for every loop pattern you actually use. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1for Loop Basics
  2. 2range()
  3. 3enumerate()
  4. 4zip()
  5. 5while Loops
  6. 6break, continue, for-else
  7. 7itertools (Standard Library)
  8. 8Comprehension vs Loop Performance
  9. 9Looping Over Dictionaries
for Loop Basicsrange()enumerate()zip()while Loopsbreak, continue, for-elseitertools (Standard Library)Comprehension vs Loop PerformanceLooping Over Dictionaries

for Loop Basics

Python for loops iterate over any iterable: lists, strings, dicts, ranges, generators.

Iterate over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
# apple
# banana
# cherry
Iterate over a string
for ch in 'hello':
    print(ch, end=' ')
# h e l l o
Ignored loop variable (_)
for _ in range(3):
    print('Hello')   # prints 3 times

range()

range(stop) produces 0 to stop-1. range(start, stop, step) gives full control. Lazy: uses nearly zero memory.

Basic range patterns
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]
Count down
list(range(5, 0, -1))   # => [5, 4, 3, 2, 1]
Inclusive range (add 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]
O(1) membership test
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(...)).

Basic enumerate
names = ['Alice', 'Bob', 'Carol']
for i, name in enumerate(names):
    print(f'{i}: {name}')
# 0: Alice
# 1: Bob
# 2: Carol
1-based indexing with start=
for num, name in enumerate(names, start=1):
    print(f'{num}. {name}')
# 1. Alice
# 2. Bob
# 3. Carol
Anti-pattern: range(len(...))
# 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.

Basic zip
names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
    print(f'{name}: {score}')
# Alice: 85
# Bob: 92
zip truncates silently
a = [1, 2, 3]
b = ['x', 'y']
list(zip(a, b))   # => [(1, 'x'), (2, 'y')]
# 3 is silently dropped!
zip(strict=True) (Python 3.10+)
list(zip([1, 2, 3], ['x', 'y'], strict=True))
# ValueError: zip() argument 2 is shorter than argument 1

Use strict=True when mismatched lengths indicate a bug in your data.

Unzip with zip(*)
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.

Basic while
count = 0
while count < 5:
    print(count)
    count += 1
# 0, 1, 2, 3, 4
Sentinel pattern (while True + break)
while True:
    line = input('> ')
    if line == 'quit':
        break
    print(f'You said: {line}')
Consume a collection
stack = [1, 2, 3]
while stack:
    item = stack.pop()
    print(item)
# 3, 2, 1

break, continue, for-else

break: exit loop entirely
for n in range(10):
    if n == 5:
        break
    print(n, end=' ')
# 0 1 2 3 4
continue: skip to next iteration
for n in range(6):
    if n % 2 == 0:
        continue
    print(n, end=' ')
# 1 3 5
for-else: runs only if no break
for item in items:
    if matches(item):
        result = item
        break
else:
    result = None   # no match found (no break occurred)
for-else: prime check
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 prime

itertools (Standard Library)

The itertools module provides memory-efficient iterator building blocks.

chain: concatenate iterables
from itertools import chain
list(chain([1, 2], [3, 4], [5]))
# => [1, 2, 3, 4, 5]
islice: slice an iterator
from itertools import islice
list(islice(range(100), 5, 10))
# => [5, 6, 7, 8, 9]
cycle: repeat forever
from itertools import cycle, islice
list(islice(cycle(['a', 'b', 'c']), 7))
# => ['a', 'b', 'c', 'a', 'b', 'c', 'a']
pairwise: adjacent pairs (Python 3.10+)
from itertools import pairwise
list(pairwise([1, 2, 3, 4]))
# => [(1, 2), (2, 3), (3, 4)]
product: Cartesian product
from itertools import product
list(product('AB', '12'))
# => [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
groupby: group consecutive items
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

Comprehension is faster for simple transforms
# 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.

Generator for memory efficiency
# 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

Keys (default)
d = {'a': 1, 'b': 2, 'c': 3}
for k in d:
    print(k, end=' ')
# a b c
Values
for v in d.values():
    print(v, end=' ')
# 1 2 3
Key-value pairs
for k, v in d.items():
    print(f'{k}={v}', end=' ')
# a=1 b=2 c=3
Enumerate dict items
for i, (k, v) in enumerate(d.items()):
    print(f'{i}: {k}={v}')
# 0: a=1
# 1: b=2
# 2: c=3
Learn Python in Depth
Python Comprehensions Practice →Python Collections Practice →Python Strings Practice →
Warm-up1 / 2

Can you write this from memory?

Iterate over items and print each item

See Also
List Comprehensions →Dictionary Methods →

Start Practicing Python

Free daily exercises with spaced repetition. No credit card required.

← Back to Python Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.