[Tutor] Better structure?

Jacob S. keridee at jayco.net
Fri Feb 4 02:26:05 CET 2005


> Although, (and this will be rough) a list comprehension would be
> probably do the same thing
> j=[1, 2,3,4, 5,6,7,8]
>
> q = [if not item % 2 for item in j]
>
> I really think I've got that 'if not item % 2' wrong, as I can't test
> it, but I'd be hoping for
> print q
> [1, 3, 5, 7]


Backwards. ;-)

q = [item for item in j if not item % 2 == 0]

A word of warning. You want odd numbers, so even if the syntax was correct 
for your list comprehension, you would have gotten even numbers -- item % 2 
would register False if item %2 == 0, then not False would be True so you 
would get all of the items that were even. Does that make sense?
You could also do

q = [item for item in j if item % 2]

Which says if item % 2 is True (not equal to False, 0) then append item to 
q. Okay, so that's not exactly what it says
HTH,
Jacob





More information about the Tutor mailing list