capypad
0 day streak
python / beginner
Snippet

Simple List Comprehensions

List comprehensions offer a shorter syntax to create a new list based on the values of an existing list, applying an expression to every item.

snippet.py
python
1
2
numbers = [1, 2, 3]
squares = [n * n for n in numbers]
Breakdown
1
numbers = [1, 2, 3]
Create a list of integers.
2
squares = [n * n for n in numbers]
Create a new list by multiplying each number in the original list by itself.