Question №15
Remaining:
What is list comprehension and how to use it?
Sample Answer
Show Answer by Default
List comprehension is a concise way to create a new list from an existing collection in a single line.
Syntax:
[expression for item in iterable]
Examples:
# Squares of numbers squares = [x ** 2 for x in range(6)] # [0, 1, 4, 9, 16, 25] # Equivalent with a loop squares = [] for x in range(6): squares.append(x ** 2)
With condition (filtering):
# Only even numbers evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
With if/else condition (transformation):
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)] # ['even', 'odd', 'even', 'odd', 'even']
Nested comprehensions:
# Multiplication table matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)] # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Analogs for other types:
# Dict comprehension squares_dict = {x: x ** 2 for x in range(5)} # Set comprehension unique_lengths = {len(word) for word in ["cat", "dog", "fox"]}
Important:
Avoid overusing complex nested comprehensions — if the expression is hard to read, use a regular loop instead.
