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 sequence.
snippet.py
1
2
3
nums = [1, 2, 3, 4]doubled = [x * 2 for x in nums]print(doubled)
Breakdown
1
[x * 2 for x in nums]
Loops through 'nums', multiplies each 'x' by 2, and collects the results into a new list.