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

Andre Engels andreengels at gmail.com
Fri Apr 22 12:17:47 CEST 2011


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]

-- 
André Engels, andreengels at gmail.com



More information about the Python-ideas mailing list