Transform a list
Filter and transform values with a comprehension.
A list comprehension builds a fresh list from an iterable. Read [n * n for n in numbers if n % 2 == 0] from the middle. For each number, check the condition, then evaluate the expression for qualifying items.
Comprehensions suit short transformations. A regular loop is easier to follow when each item needs several steps. Similar syntax with braces builds sets or dictionaries.
The comprehension examines every member of the original list.
Try it yourself
Build a list of doubled odd numbers from 1 through 5 and print the list.
Target output
[2, 6, 10]Show a hint
Test for a remainder of 1 and use n * 2 as the expression.
Output
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
numbers = [1, 2, 3, 4, 5]
doubles = [n * 2 for n in numbers if n % 2 == 1]
print(doubles)