# Using a for loop
numbers = []
for i in range(1, 6):
numbers.append(i)
print("Using for loop:", numbers)Using for loop: [1, 2, 3, 4, 5]
This document covers two powerful Python features that help you write more concise and elegant code:
Both features are fundamental to writing Pythonic code and are widely used in data science, web development, and general programming.
List comprehension provides a concise way to create lists based on existing lists or other iterable objects. Instead of using multiple lines with loops and conditions, you can often accomplish the same task in a single line.
Basic Syntax:
[expression for item in iterable if condition]Traditional approach:
# Using a for loop
numbers = []
for i in range(1, 6):
numbers.append(i)
print("Using for loop:", numbers)Using for loop: [1, 2, 3, 4, 5]
List comprehension approach:
# Using list comprehension
numbers = [i for i in range(1, 6)]
print("Using list comprehension:", numbers)Using list comprehension: [1, 2, 3, 4, 5]
Traditional approach:
# Squaring numbers with a loop
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print("Squares using loop:", squares)Squares using loop: [1, 4, 9, 16, 25]
List comprehension approach:
# Squaring numbers with list comprehension
squares = [i ** 2 for i in range(1, 6)]
print("Squares using comprehension:", squares)Squares using comprehension: [1, 4, 9, 16, 25]
# Get only even numbers from 1 to 10
even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print("Even numbers:", even_numbers)Even numbers: [2, 4, 6, 8, 10]
# Convert a list of words to uppercase
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print("Uppercase words:", uppercase_words)Uppercase words: ['HELLO', 'WORLD', 'PYTHON']
# Create a 3x3 matrix
matrix = [[i + j for j in range(3)] for i in range(0, 9, 3)]
print("Matrix:")
for row in matrix:
print(row)Matrix:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
# Flatten a 2D list into 1D
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print("Flattened list:", flattened)Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Numbers divisible by 2 AND 3 (i.e., divisible by 6)
numbers = [num for num in range(1, 31) if num % 2 == 0 if num % 3 == 0]
print("Numbers divisible by both 2 and 3:", numbers)Numbers divisible by both 2 and 3: [6, 12, 18, 24, 30]
# Categorize numbers as even or odd
numbers = range(1, 11)
categorized = ["Even" if num % 2 == 0 else "Odd" for num in numbers]
print("Categorized:", categorized)Categorized: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
# Create a dictionary of numbers and their squares
square_dict = {num: num ** 2 for num in range(1, 6)}
print("Square dictionary:", square_dict)Square dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Combine two lists using zip
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = [f"{name} is {age} years old" for name, age in zip(names, ages)]
for item in combined:
print(item)Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old
Lambda functions are small, anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression. They are useful for short, simple operations that you don’t want to formally define with def.
Basic Syntax:
lambda arguments: expression# Regular function
def add(x, y):
return x + y
print("Regular function:", add(3, 5))
# Lambda equivalent
add_lambda = lambda x, y: x + y
print("Lambda function:", add_lambda(3, 5))Regular function: 8
Lambda function: 8
# Square a number
square = lambda x: x ** 2
print("Square of 7:", square(7))Square of 7: 49
# Double each number in a list
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print("Doubled numbers:", doubled)Doubled numbers: [2, 4, 6, 8, 10]
# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", evens)Even numbers: [2, 4, 6, 8, 10]
# Get the length of strings
words = ["apple", "banana", "cherry"]
lengths = list(map(lambda word: len(word), words))
print("Word lengths:", lengths)Word lengths: [5, 6, 6]
# Sort a list of tuples by the second element
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78), ("Diana", 95)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print("Students sorted by grade:")
for student in sorted_students:
print(f"{student[0]}: {student[1]}")Students sorted by grade:
Diana: 95
Bob: 92
Alice: 85
Charlie: 78
from functools import reduce
# Calculate the product of all numbers
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product of all numbers:", product)Product of all numbers: 120
# Create a calculator using lambdas
operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y if y != 0 else "Cannot divide by zero"
}
print("10 + 5 =", operations['add'](10, 5))
print("10 - 5 =", operations['subtract'](10, 5))
print("10 * 5 =", operations['multiply'](10, 5))
print("10 / 5 =", operations['divide'](10, 5))10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2.0
# Categorize numbers as positive, negative, or zero
numbers = [-5, 0, 3, -2, 7, 0, -1]
categories = list(map(lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero", numbers))
print("Categories:", categories)Categories: ['Negative', 'Zero', 'Positive', 'Negative', 'Positive', 'Zero', 'Negative']
# Apply different operations based on condition
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [(lambda x: x ** 2 if x % 2 == 0 else x ** 3)(num) for num in numbers]
print("Squares for even, cubes for odd:", result)Squares for even, cubes for odd: [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]
# Create a function that returns a function
multiply_by = lambda x: lambda y: x * y
double = multiply_by(2)
triple = multiply_by(3)
print("Double of 5:", double(5))
print("Triple of 5:", triple(5))Double of 5: 10
Triple of 5: 15
# Get squares of even numbers
numbers = range(1, 11)
even_squares = [num ** 2 for num in numbers if (lambda x: x % 2 == 0)(num)]
print("Squares of even numbers:", even_squares)Squares of even numbers: [4, 16, 36, 64, 100]
# Process a list of products
products = [
{"name": "Apple", "price": 1.20},
{"name": "Banana", "price": 0.50},
{"name": "Orange", "price": 1.50},
{"name": "Mango", "price": 2.00}
]
# Get names of products priced above $1
expensive = [p["name"] for p in products if (lambda x: x["price"] > 1.0)(p)]
print("Expensive products:", expensive)Expensive products: ['Apple', 'Orange', 'Mango']
# Transform and filter data in one step
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Square even numbers, cube odd numbers, then filter those greater than 50
result = list(filter(
lambda x: x > 50,
map(lambda x: x ** 2 if x % 2 == 0 else x ** 3, data)
))
print("Transformed and filtered:", result)Transformed and filtered: [125, 343, 64, 729, 100]
✅ DO use when: - Creating a new list from an existing iterable - The operation is simple and readable - You need to filter and transform data
❌ DON’T use when: - The logic is too complex (use regular loops) - You need to perform multiple operations per item - Readability suffers
✅ DO use when: - You need a simple function for a short period - Working with map(), filter(), sorted(), etc. - The function is used only once
❌ DON’T use when: - The function is complex - You need documentation or multiple statements - The function will be reused multiple times (use def instead)
[0, 10, 20, 30] to FahrenheitList comprehension and lambda functions are powerful tools in Python that help you:
Remember: Just because you can use these features doesn’t mean you always should. Code clarity should always be your primary concern. Use these tools when they make your code more readable and maintainable, not just to show off!