Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

I start with a list

L = [1,2,3,4,5,6,7,8,9,10]

I'm collecting all even numbers like this

new = []
for n in L:
  if n % 2 == 0:
    new.append(n) 

I am not sure how I would specify the condition in the following statement

new = [n for n in L]
share|improve this question
This question would probably have been better suited for stackoverflow, but now that it's here, aditsu's answer is exactly what you've asked for. – primo Feb 27 at 17:38
-1 for off topic. – Shmiddty Feb 27 at 17:52
Hi, Keikoku. This is not a general help site, but a place where we pose certain classes of puzzles for the amusement of other users. It is expected that these puzzles be interesting and have multiple types of solutions so that we can explore different approaches, and to insure this you generally need to have a solution in hand. Please have a look around. – dmckee Feb 27 at 18:10

closed as not a real question by primo, Steven Rumbalski, dmckee Feb 27 at 18:08

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

1 Answer

up vote 0 down vote accepted

You can do [n for n in L if n%2==0]

share|improve this answer
An alternative, using the built-in filter function: new = filter(lambda n: n%2 == 0, L) – primo Feb 27 at 17:43
Yes, but I heard it's not considered very "idiomatic/pythonic" – aditsu Feb 27 at 17:44
1  
Perhaps it would be more "Schematic"? (i.e. sounds like the kind of thing you'd do in Scheme.) – Joe Z. Feb 27 at 18:15
filter was in Python before list comprehensions were a twinkle in Guido's eye. It used to be very pythonic - but it's not any more - and it's nearly always slower! – gnibbler Feb 27 at 20:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.