default value in list comprehension

A

AlienBaby

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.
 
E

eb303

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.

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

HTH
- Eric -
 
A

AlienBaby

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.


Matt.

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

HTH
 - Eric -- Hide quoted text -

- Show quoted text -

Ahh. Gotcha, thankyou :)
 
B

Bruno Desthuilliers

eb303 a écrit :
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.

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

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]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top