Python Comprehensions
PythonComprehensions are a Pythonic way to create lists, dicts, and sets in a single line. They're cleaner and faster than loops.
Key Points
- List comprehension:
[expr for item in iterable if condition] - Dict comprehension:
{key: value for item in iterable} - Set comprehension:
{expr for item in iterable} - Replaces multi-line loops with one elegant line
- Very common in interviews and production code
Example — PYTHON
# Basic list comprehension
squares = [x**2 for x in range(1, 11)]
print(f"Squares: {squares}")
# With condition
evens = [x for x in range(1, 21) if x % 2 == 0]
print(f"Evens: {evens}")
# String processing
names = ["rahul", "priya", "amit", "sara"]
capitalized = [name.title() for name in names]
print(f"Names: {capitalized}")
# Nested comprehension — flatten
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(f"Flat: {flat}")
# Dict comprehension
marks = {"Rahul": 85, "Priya": 92, "Amit": 78, "Sara": 45}
passed = {name: mark for name, mark in marks.items() if mark >= 50}
print(f"Passed: {passed}")
# Word length dict
words = ["Python", "Java", "Go", "JavaScript"]
lengths = {w: len(w) for w in words}
print(f"Lengths: {lengths}")
# Set comprehension
sentence = "hello world hello python world"
unique_words = {word for word in sentence.split()}
print(f"Unique: {unique_words}")
# FizzBuzz one-liner
fizzbuzz = ["FizzBuzz" if i%15==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else i for i in range(1, 16)]
print(fizzbuzz) Result
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Evens: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Names: ['Rahul', 'Priya', 'Amit', 'Sara']
Flat: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Passed: {'Rahul': 85, 'Priya': 92, 'Amit': 78}
Lengths: {'Python': 6, 'Java': 4, 'Go': 2, 'JavaScript': 10}
Unique: {'hello', 'world', 'python'}
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz']
Evens: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Names: ['Rahul', 'Priya', 'Amit', 'Sara']
Flat: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Passed: {'Rahul': 85, 'Priya': 92, 'Amit': 78}
Lengths: {'Python': 6, 'Java': 4, 'Go': 2, 'JavaScript': 10}
Unique: {'hello', 'world', 'python'}
[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz']