map, filter, zip, enumerate & Comprehensions
Write cleaner, faster Python with built‑in functional tools. Then build a data processing pipeline that ties together variables, loops, conditionals, collections, and these powerful functions.
map
Apply a function to every item
filter
Keep items that pass a test
zip
Combine iterables element‑wise
enumerate
Loop with index & value
Comprehensions
Lists, dicts, sets in one line
map – Apply a Function to Every Element
map(func, iterable) runs func on each item and returns a map object (lazy iterator).
# Double each number
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
# Convert strings to integers
str_nums = ["10", "20", "30"]
int_nums = list(map(int, str_nums))
print(doubled) # [2, 4, 6, 8]
print(int_nums) # [10, 20, 30]
filter – Keep Elements That Satisfy a Condition
filter(func, iterable) returns items for which func(item) is truthy.
nums = [5, 12, 17, 18, 24, 32]
# Keep even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
# Keep words longer than 4 letters
words = ["apple", "cat", "banana", "dog"]
long_words = list(filter(lambda w: len(w) > 4, words))
print(evens) # [12, 18, 24, 32]
print(long_words) # ['apple', 'banana']
zip – Combine Multiple Iterables
zip(*iterables) returns tuples of corresponding elements. Stops at the shortest iterable.
names = ["Aarav", "Priya", "Rohan"]
scores = [95, 88, 76]
# Pair names with scores
paired = list(zip(names, scores))
print(paired) # [('Aarav', 95), ('Priya', 88), ('Rohan', 76)]
# Unzipping
pairs = [('a', 1), ('b', 2)]
letters, numbers = zip(*pairs)
print(letters) # ('a', 'b')
print(numbers) # (1, 2)
enumerate – Loop with Index & Value
enumerate(iterable, start=0) yields (index, element) pairs.
subjects = ["Maths", "Science", "English"]
# Default start = 0
for i, subj in enumerate(subjects):
print(f"{i}: {subj}")
# Start at 1 (human‑friendly)
print()
for i, subj in enumerate(subjects, start=1):
print(f"{i} → {subj}")
List Comprehension
Syntax: [expression for item in iterable if condition]
# Squares of 1‑5
squares = [x**2 for x in range(1, 6)]
# Even numbers 0‑9
evens = [x for x in range(10) if x % 2 == 0]
# Uppercase words
words = ["hello", "world"]
upper = [w.upper() for w in words]
print(squares) # [1, 4, 9, 16, 25]
print(evens) # [0, 2, 4, 6, 8]
print(upper) # ['HELLO', 'WORLD']
Dictionary Comprehension
Syntax: {key_expr: value_expr for item in iterable if condition}
# Word → length
words = ["apple", "banana", "cherry"]
word_len = {w: len(w) for w in words}
# Square numbers
squares = {x: x**2 for x in range(1, 5)}
# Filter high grades
grades = {"maths": 95, "science": 88, "history": 72}
high = {k: v for k, v in grades.items() if v >= 80}
print(word_len) # {'apple':5, 'banana':6, 'cherry':6}
print(squares) # {1:1,2:4,3:9,4:16}
print(high) # {'maths':95, 'science':88}
Set Comprehension
Syntax: {expression for item in iterable if condition} – curly braces, no colons.
# Unique lengths
words = ["apple", "banana", "cherry", "date"]
lengths = {len(w) for w in words}
# Squares (duplicates removed)
squares = {x**2 for x in range(-3, 4)}
print(lengths) # {5, 6}
print(squares) # {0, 1, 4, 9}
🎯 Mini Project: Data Processing Pipeline
This project uses map, filter, zip, enumerate, list/dict/set comprehensions, plus variables, input validation, loops, conditionals, lists, tuples, sets, and dictionaries – everything you’ve learned so far. You’ll build a sales data pipeline that reads raw transactions, cleans data, computes metrics, and generates reports.
"""
Data Processing Pipeline – Complete Mini Project
Concepts used: map, filter, zip, enumerate, comprehensions (list, dict, set),
variables, type casting, loops, conditionals, lists, tuples, sets, dicts.
"""
def main():
# Sample raw transaction data (list of tuples: (product, category, price, quantity))
transactions = [
("Laptop", "Electronics", 75000, 2),
("Mouse", "Electronics", 1500, 5),
("Notebook", "Stationery", 80, 20),
("Pen", "Stationery", 25, 50),
("Desk", "Furniture", 12000, 1),
("Chair", "Furniture", 8000, 3),
("USB Cable", "Electronics", 400, 8),
]
# 1. Use map to calculate total revenue per transaction (price * quantity)
revenues = list(map(lambda t: t[2] * t[3], transactions))
print("Revenue per transaction:", revenues)
# 2. Use filter to keep only high‑value transactions (revenue > 10000)
high_value = list(filter(lambda i: revenues[i] > 10000, range(len(transactions))))
print("High‑value transaction indices:", high_value)
# 3. Use zip to pair each transaction with its revenue
paired = list(zip(transactions, revenues))
print("First paired:", paired[0])
# 4. Use enumerate to display numbered transactions
print("\n📋 ALL TRANSACTIONS (numbered):")
for idx, t in enumerate(transactions, 1):
product, category, price, qty = t
print(f"{idx}. {product} | {category} | ₹{price} x {qty} = ₹{price*qty}")
# 5. List comprehension: extract all product names
products = [t[0] for t in transactions]
print("\nProducts:", products)
# 6. Set comprehension: unique categories
categories = {t[1] for t in transactions}
print("Unique categories:", categories)
# 7. Dictionary comprehension: category -> total revenue
cat_rev = {}
for t, rev in zip(transactions, revenues):
cat = t[1]
cat_rev[cat] = cat_rev.get(cat, 0) + rev
print("Category revenue:", cat_rev)
# 8. User interaction: filter by category (using dictionary and input)
print("\n🔍 Filter transactions by category")
for cat in categories:
print(f" - {cat}")
choice = input("Enter category: ").strip()
filtered = [t for t in transactions if t[1] == choice]
if filtered:
print(f"Transactions in {choice}:")
for t in filtered:
print(f" {t[0]} (₹{t[2]} x {t[3]})")
else:
print("Category not found.")
# 9. Use filter + map to get high‑revenue product names
high_rev_products = list(map(lambda i: transactions[i][0], high_value))
print("\n🏆 High‑revenue products (revenue > 10000):", high_rev_products)
# 10. Bonus: compute average transaction value using comprehension
if revenues:
avg_rev = sum(revenues) / len(revenues)
print(f"Average transaction value: ₹{avg_rev:.2f}")
if __name__ == "__main__":
main()
– map transforms raw data (price * quantity).
– filter selects high‑value transactions.
– zip combines transactions with computed revenues.
– enumerate gives numbered output.
– List/dict/set comprehensions create clean collections.
– All previous concepts (loops, conditionals, type casting, dict merging, etc.) are used.
– Extend the pipeline with CSV file I/O, data visualisation, or advanced analytics.
Solved Practice Problems
Strengthen your understanding with these examples.
🔰 Beginner Level
1. Convert list of Celsius to Fahrenheit using map
celsius = [0, 10, 20, 30]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit) # [32.0, 50.0, 68.0, 86.0]2. Extract all names starting with 'A' using filter
names = ["Aarav", "Priya", "Anika", "Rohan"]
a_names = list(filter(lambda n: n.startswith('A'), names))
print(a_names) # ['Aarav', 'Anika']3. Create a dictionary of numbers and their cubes using dict comprehension
cubes = {n: n**3 for n in range(1, 6)}
print(cubes) # {1:1, 2:8, 3:27, 4:64, 5:125}⚡ Intermediate Level
4. Enumerate and build a dictionary of positions
fruits = ["apple", "banana", "cherry"]
pos = {fruit: idx for idx, fruit in enumerate(fruits)}
print(pos) # {'apple':0, 'banana':1, 'cherry':2}5. Use zip and dict to create a score dictionary from two lists
names = ["Aarav", "Priya", "Rohan"]
scores = [95, 88, 76]
score_dict = dict(zip(names, scores))
print(score_dict) # {'Aarav':95, 'Priya':88, 'Rohan':76}Unsolved Exercises
Challenge yourself – no solutions provided, but you can use the solved examples and the mini project as a guide.