Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

default value in list comprehension

0 views
Skip to first unread message

AlienBaby

unread,
Apr 19, 2010, 8:20:40 AM4/19/10
to
Hi,

just a quick one,

Is it possible to achieve a default value in a list comprehension
where the if-clause is false?

Ie, something similar to:

[ a for a in b if something(a) else 'default' ]

the idea being that, rather than skip a value if the if-clause is
false, to place a default value at that position in the returned list
instead.

?

Thanks,


Matt.


eb303

unread,
Apr 19, 2010, 8:23:38 AM4/19/10
to

[a if something(a) else 'default' for a in b]

HTH
- Eric -

AlienBaby

unread,
Apr 19, 2010, 8:26:42 AM4/19/10
to
>  - Eric -- Hide quoted text -
>
> - Show quoted text -

Ahh. Gotcha, thankyou :)

Bruno Desthuilliers

unread,
Apr 19, 2010, 9:20:25 AM4/19/10
to
eb303 a écrit :

Or you could have "something" taking a "default" argument and returning
either it's argument (instead of True) or the "default" one (instead of
False), and get rid of the if/else test in the list comp, ie:

def something(obj, default=False):
if whatever(obj):
return obj
else:
return default

results = [something(a, default="default") for a in b]

0 new messages