Use only some items in a list comprehension?

Viewed 872

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?

1 Answers

After writing the question, the list of related items offered an answer indirectly.

Simply put, my guess at the syntax was wrong - I just have the "if" in the wrong place. It goes after the for statement:

a = [1, 2, 3, 4, 5, 6, 7]
b = [ item for item in a if item % 2 == 0 ]

I found the answer indirectly as part of this answer, but the question is different. I wasn't able to find anything directly asking this question, so I'll leave this up for other noobs like me that are still learning basic comprehension syntax.

Related