š
List Comprehensions and Lambda Functions
Intermediate
90 XP
40 min
Lesson Content
List Comprehensions: Concise List Creation
List comprehensions provide a concise way to create lists. They're more Pythonic and often faster than traditional loops.
Basic List Comprehension
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
# Result: [0, 1, 4, 9, 16]
# List comprehension way
squares = [x ** 2 for x in range(5)]
# Result: [0, 1, 4, 9, 16]List Comprehension with Condition
# Even numbers
evens = [x for x in range(10) if x % 2 == 0]
# Result: [0, 2, 4, 6, 8]
# Filter and transform
words = ["hello", "world", "python"]
lengths = [len(word) for word in words if len(word) > 5]
# Result: [6] (only 'python' has length > 5)Nested List Comprehensions
# Matrix (list of lists)
matrix = [[i * j for j in range(3)] for i in range(3)]
# Result: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]Lambda Functions
Anonymous functions defined with lambda:
# Regular function
def add(x, y):
return x + y
# Lambda function
add = lambda x, y: x + y
# Common use: with map(), filter(), sorted()
numbers = [1, 2, 3, 4, 5]
# Map: apply function to each item
squared = list(map(lambda x: x ** 2, numbers))
# Result: [1, 4, 9, 16, 25]
# Filter: keep items that meet condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Result: [2, 4]
# Sorted: sort with custom key
students = [("Alice", 20), ("Bob", 18)]
sorted_by_age = sorted(students, key=lambda x: x[1])
# Result: [('Bob', 18), ('Alice', 20)]Dictionary and Set Comprehensions
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension
unique_lengths = {len(word) for word in ["hi", "hello", "hi"]}
# Result: {2, 5}When to Use Comprehensions
- ā Simple transformations and filters
- ā Creating lists from other iterables
- ā More readable and Pythonic
- ā Complex logic (use regular loops)
- ā When you need side effects
Example Code
Use list comprehensions to create filtered and transformed lists.
# Create a list of squares for numbers 0-9 squares = [x ** 2 for x in range(10)] print(squares) # Create a list of even numbers from 0-20 evens = [x for x in range(21) if x % 2 == 0] print(evens) # Convert strings to uppercase using list comprehension words = ["hello", "world", "python"] uppercase = [word.upper() for word in words] print(uppercase)
Expected Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ['HELLO', 'WORLD', 'PYTHON']
Study Tips
- ā¢Read the theory content thoroughly before practicing
- ā¢Review the example code to understand key concepts
- ā¢Proceed to the Practice tab when you're ready to code