capypad
0 day streak
python / beginner
Snippet

List Comprehensions

List comprehensions offer a shorter syntax when you want to create a new list based on the values of an existing list.

snippet.py
python
1
2
3
numbers = [1, 2, 3, 4]
squared = [n ** 2 for n in numbers]
print(squared)
Breakdown
1
numbers = [1, 2, 3, 4]
Defines a simple list of integers.
2
squared = [n ** 2 for n in numbers]
Creates a new list by squaring each element in the original list using a compact loop.