Reputation: 35269
I'd like to know if it is possible to use a list comprehension with if
/ else
that need not result in a list of the same length as the length of the list being processed? (ie. without the final else
)
>>> L = [0, 1, 2, 3, 4, 5, 6]
>>> [v * 10 if v < 3 else v * 2 if v > 3 else v for v in L] #if/else/if/else
[0, 10, 20, 3, 8, 10, 12]
works fine. But suppose I want to omit the 3, to get:
[0, 10, 20, 8, 10, 12] # No number 3
I would have thought this would work:
>>> [v * 10 if v < 3 else v * 2 if v > 3 for v in L] #if/else/if
But it is a syntax error..
So I thought 'maybe' this would work:
>>> [v * 10 if v < 3 else v * 2 if v > 3 else pass for v in L] #if/else/if/else pass
But it doesn't..
This is a curiosity question, I realise this is not neccessarily the most readable/appropriate approach to the above processing.
Am I missing something? Can it be done? (I'm on python 2.6.5)
Upvotes: 3
Views: 12673
Reputation: 34698
Whats wrong with doing
out = []
for v in L:
if v < 3:
out.append(v * 10)
elif v > 3:
out.append(v * 2)
else:
pass
Upvotes: -2
Reputation: 212895
Put the filtering condition after the loop:
[v * 10 if v < 3 else v * 2 for v in L if v != 3]
returns
[0, 10, 20, 8, 10, 12]
Upvotes: 4
Reputation: 318518
Yes, that's possible:
[foo for foo in bar if foo.something]
Or in your case:
[v * 10 if v < 3 else v * 2 for v in L if v != 3]
I's also mentioned in the docs.
Upvotes: 14