capypad
0 day streak
python / beginner
Snippet

Simple List Comprehension

List comprehension provides a concise way to create lists by applying an expression to each item in an existing iterable.

snippet.py
python
1
2
3
numbers = [1, 2, 3]
squares = [x * x for x in numbers]
print(squares)
Breakdown
1
numbers = [1, 2, 3]
A starting list of numbers.
2
squares = [x * x for x in numbers]
Creates a new list where every number is squared.
3
print(squares)
Outputs the list of squared values: [1, 4, 9].