2

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?

LightCC
  • 9,804
  • 5
  • 52
  • 92
  • Ok [this question](https://stackoverflow.com/questions/15474933/list-comprehension-with-if-statement) is definitely a duplicate after reading through it, the rest are close, but not the same. Still not sure why none of these popped up on searches though - even the "related answers" list given before posting didn't have any of these new linked ones. I'm not surprised this was already answered though! Cheers!! – LightCC May 21 '20 at 03:53

1 Answers1

3

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.

LightCC
  • 9,804
  • 5
  • 52
  • 92
  • 1
    Hmm. I could have sworn this sort of thing comes up constantly. But everything I can find that *seems* like a duplicate candidate, has OP already knowing how to do it, and asking some more subtle follow-on question. :/ – Karl Knechtel May 21 '20 at 01:36
  • 2
    Please also ___accept your own answer___. I think your question has been completely answered in terms of using list comprehension. (I meant not to forget to do so after the 48 hours wait-period ;)) – Ivo Mori May 21 '20 at 01:39
  • @KarlKnechtel I'm sure it does comes up constantly, but in my Python journey, first time I ran into this wrinkle and finally looked it up. :) When I start looking at the linked answers, almost all of them do give the way to do this, but the questions are not asking for this specific point. Maybe that's why it's not coming up on my searches, or I'm just using the wrong search terms. Who knows... :) – LightCC May 21 '20 at 03:45