List Comprehensions in Python - DJC
List comprehensions are a concise and readable way to create lists in a single line of code.
Syntax:
[expression for element in iterable if condition]
Basic example:
squares = [x**2 for x in range(10)]
print(squares)
With a condition:
evens = [x for x in range(20) if x % 2 == 0]
Nesting:
matrix = [[i * j for j in range(3)] for i in range(3)]
Although powerful, it’s recommended not to overuse nested comprehensions if they affect readability.