Surely this is possible. Searches turned up nil.
How do I create a list comprehension (or any type of comprehension) which only selects certain values from the source list or other iterable?
Example
Let's say I just want even numbers from a list. For example, given:
a = [1, 2, 3, 4, 5, 6, 7]
I can do this easily with a for loop, but need to initialize a variable:
b = []
for item in a:
b.append(item) if item % 2 == 0
print(b)
Which returns:
[2, 4, 6]
But how to do this in a list comprehension and without initializing a variable first?
Failed List Comprehensions
I tried:
b = [ item if item % 2 == 0 for item in a ]
Which returns SyntaxError: invalid syntax
after the for
.
I if I add an else xxx
it works, but then I must have the same number of total elements:
b = [ item if item % 2 == 0 else None for item in a ]
which returns:
[None, 2, None, 4, None, 6, None]
How can I remove or filter out items from the final comprehension if they don't meet the criteria?