[Python-ideas] ('blue', 'red', 'orange' if something, 'green')

MRAB python at mrabarnett.plus.com
Fri Apr 22 12:31:15 CEST 2011


On 22/04/2011 11:17, Andre Engels wrote:
> On Fri, Apr 22, 2011 at 11:59 AM, cool-RR<cool-rr at cool-rr.com>  wrote:
>> Here's an idea that would have helped me today while coding. Allow something
>> like this:
>>      ('blue', 'red', 'orange' if some_condition, 'green')
>> So 'orange' is included in the tuple only if `some_condition` evaluates to
>> `True`. This could be applied to list literals, tuple literals, set
>> literals, and possibly dict literals, though the latter might be too clunky.
>> I expect this to be rejected, but I really couldn't think of an elegant way
>> to achieve the same thing with existing syntax.
>
> First note: If you can just remove an element in the middle and still
> have the same time of object, then logically it would be a list, not
> an array. But things that semantically are lists are indeed sometimes
> made array for performance reasons, so that's not a weird thing to do.
>
> Having said that, I don't think it's going to make it. Normally
> there's exactly one element between each pair of commas; if we're
> going to give up that, I'm not sure this is the best way to do it.
>
> As for other ways to do it, they are not as elegant but they certainly do exist:
>
> ('blue', 'red') + (('orange',) if some_condition else ()) + 'green'
>
> [c for c in ('blue', 'red', 'orange', 'green') if c != 'orange' or
> some_condition]
>
You could write:

     def make_tuple(*items):
         return tuple(x for x in items if x is not None)

and then:

 >>> make_tuple('blue', 'red', 'orange' if some_condition else None, 
'green')
('blue', 'red', 'green')
 >>> some_condition = True
 >>> make_tuple('blue', 'red', 'orange' if some_condition else None, 
'green')
('blue', 'red', 'orange', 'green')



More information about the Python-ideas mailing list