Comprehensions and Built-ins
Write concise solutions using list/dict/set comprehensions, map, filter, zip, enumerate, and sorted with key functions.
Comprehensions and Built-ins is a free DSA Interview Prep lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DSA Interview Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
List Comprehensions: Concise Filtering
A list comprehension turns a for-loop-plus-append into one clean line: [expr for item in iterable if condition]. It is a little faster and signals Python fluency.
# Traditional loop
squares = []
for n in range(1, 6):
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With filter
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]Nested Comprehensions for 2D Grids
Nested comprehensions build 2D grids — the standard way to set up a DP table. Avoid [[0]*C]*R, which shares one inner list across every row. The code shows the fix.
# WRONG: all rows are the same object!
bad = [[0] * 3] * 3
bad[0][0] = 9
print(bad) # [[9,0,0],[9,0,0],[9,0,0]] oops!
# CORRECT: each row is a separate list
good = [[0] * 3 for _ in range(3)]
good[0][0] = 9
print(good) # [[9,0,0],[0,0,0],[0,0,0]]Dict and Set Comprehensions
Dict and set comprehensions use braces: {k: v for ...} for a dict, {expr for ...} for a set. Both can filter, so you can transform or dedupe in a single line.
# Dict comprehension: square lookup
sq_map = {n: n**2 for n in range(1, 6)}
print(sq_map) # {1:1, 2:4, 3:9, 4:16, 5:25}
# Set comprehension: unique lengths
words = ['cat', 'dog', 'elephant', 'ant']
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {3, 8} (order varies)Generator Expressions: Memory-Efficient
Wrap a comprehension in () and you get a generator that yields values one at a time, saving memory. Feed it straight into sum, max, or any over huge sequences.
# List comprehension builds all values at once
total = sum([n**2 for n in range(1_000_000)])
# Generator yields one at a time — lower memory
total = sum(n**2 for n in range(1_000_000))
print(total) # 333332833333500000
# any/all with generators short-circuit early
nums = [4, 6, 8, 3, 10]
has_odd = any(n % 2 == 1 for n in nums)
print(has_odd) # True (stops at 3)map() and filter(): Functional Style
map applies a function to every item; filter keeps the ones that pass a test. Both are lazy, so wrap in list() to see results. Comprehensions are often clearer.
nums = [1, 2, 3, 4, 5]
# map: apply function to each element
doubled = list(map(lambda n: n * 2, nums))
print(doubled) # [2, 4, 6, 8, 10]
# filter: keep elements passing predicate
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # [2, 4]
# Equivalent comprehensions (often preferred)
doubled = [n * 2 for n in nums]
evens = [n for n in nums if n % 2 == 0]zip(): Pairing Sequences
zip pairs two sequences and stops at the shorter one — the clean way to loop two lists at once. The trick zip(*matrix) transposes a 2D list. See the code.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
pairs = list(zip(keys, values))
print(pairs) # [('a',1), ('b',2), ('c',3)]
# Build dict from two lists
d = dict(zip(keys, values))
print(d) # {'a':1, 'b':2, 'c':3}
# Transpose a matrix
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transposed = [list(row) for row in zip(*matrix)]
print(transposed) # [[1,4,7],[2,5,8],[3,6,9]]enumerate(): Index Plus Value
enumerate gives you (index, value) as you loop — cleaner than range(len(lst)) and free of off-by-one slips. Use the start option to begin counting at 1.
fruits = ['apple', 'banana', 'cherry']
# Instead of: for i in range(len(fruits)):
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 apple / 1 banana / 2 cherry
# Start from 1
for i, fruit in enumerate(fruits, 1):
print(f'{i}. {fruit}')
# 1. apple / 2. banana / 3. cherrysorted() with Key Functions
sorted returns a new sorted list and takes a key function for custom order. Sort by length, by a tuple field, or case-insensitively. The code shows multi-key sorts.
# Sort by second element of tuple
intervals = [(1,3),(2,1),(0,5)]
print(sorted(intervals, key=lambda x: x[1]))
# [(2,1),(1,3),(0,5)]
# Sort strings case-insensitively
words = ['Banana', 'apple', 'Cherry']
print(sorted(words, key=str.lower))
# ['apple', 'Banana', 'Cherry']
# Sort by multiple keys: first by length, then alphabetically
words = ['fig', 'apple', 'ant', 'kiwi']
print(sorted(words, key=lambda w: (len(w), w)))
# ['ant', 'fig', 'kiwi', 'apple']min() and max() with Key
min and max take a key too, so you can grab the element with the smallest or largest mapped value in one call — like the longest word. See the code.
words = ['banana', 'fig', 'strawberry', 'kiwi']
longest = max(words, key=len)
print(longest) # strawberry
shortest = min(words, key=len)
print(shortest) # fig
# Find interval with earliest end
intervals = [(2,6),(1,3),(4,5)]
earlist_end = min(intervals, key=lambda x: x[1])
print(earlist_end) # (1, 3)any() and all() for Short-Circuit Checks
any stops at the first truthy item; all stops at the first falsy one. Both short-circuit, so paired with a generator they test conditions fast and lazily.
nums = [2, 4, 6, 7, 8]
all_even = all(n % 2 == 0 for n in nums)
print(all_even) # False (7 is odd)
has_large = any(n > 5 for n in nums)
print(has_large) # True (6 qualifies, stops there)
# Practical: check if sudoku row has no duplicates
row = [1, 2, 3, 4, 5, 6, 7, 8, 9]
valid = all(1 <= n <= 9 for n in row) and len(set(row)) == 9
print(valid) # Truesum(), abs(), and divmod()
Three math helpers show up everywhere: sum, abs, and divmod. divmod(a, b) returns both the quotient and remainder at once — perfect for pulling digits.
# sum with generator
print(sum(n**2 for n in range(1, 6))) # 55
# abs for distance problems
print(abs(-7)) # 7
# divmod for digit extraction
num = 1234
digits = []
while num:
num, d = divmod(num, 10)
digits.append(d)
digits.reverse()
print(digits) # [1, 2, 3, 4]Quick Check
Quick check — let us see how the comprehensions and built-ins landed. One question, you have got this. ✅
Lesson Recap
Recap: comprehensions turn loops into one-liners, built-ins like zip and sorted take key functions, and generators save memory for single-pass work.
Frequently asked questions
Is the “Comprehensions and Built-ins” lesson free?
Yes — the full text of “Comprehensions and Built-ins” is free to read here on the web, and the DSA Interview Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DSA Interview Prep course, upgrade to CoddyKit PRO.
What will I learn in “Comprehensions and Built-ins”?
Write concise solutions using list/dict/set comprehensions, map, filter, zip, enumerate, and sorted with key functions. You practise DSA Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DSA Interview Prep?
No prior experience is required. DSA Interview Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Comprehensions and Built-ins” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DSA Interview Prep lesson?
Yes. Every DSA Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Lists, Tuples, and Slicing
- Dictionaries and Sets in Python
- Comprehensions and Built-ins
- Functions, Closures, and Lambda