capypad
0 day streak
python / beginner
Snippet

Basic List Comprehensions

List comprehensions provide a concise way to create new lists by applying an expression to each item in an existing list.

snippet.py
python
1
2
3
numbers = [1, 2, 3, 4]
doubled = [n * 2 for n in numbers]
print(doubled)
Breakdown
1
numbers = [1, 2, 3, 4]
Defines a starting list of integers.
2
doubled = [n * 2 for n in numbers]
Iterates through 'numbers' and multiplies each element by 2 to build a new list.