Search code examples
pythonif-statementconditional-expressions

Is it possible to have an if inside a tuple?


I'd like to build something like:

A = (
  'parlament',
  'queen/king' if not country in ('england', 'sweden', …),
  'press',
  'judges'
)

Is there any way to build a tuple like that?

I tried

'queen/king' if not country in ('england', 'sweden', …) else None,
'queen/king' if not country in ('england', 'sweden', …) else tuple(),
'queen/king' if not country in ('england', 'sweden', …) else (),

but nothing is working, there doesn't seem to be an tuple-None-element, so I have a 3-tuple for all countries beside England, Sweden, etc. for which I get a 4-tuple


Solution

  • I ran into a similar problem. You can use the spread operator *:

    A = (
      'parlament',
      *(('queen/king',) if not country in ('england', 'sweden', …) else tuple()),
      'press',
      'judges'
    )
    

    Looks a little bit complicated but does exactly what is requested. First it "packs" the whatever answer is needed into a tuple (resulting either in an empty tuple or in a single–element tuple). Then, it "unpacks" the resulting tuple and merges it into the right place in the main outer tuple