Is it possible to have an if inside a tuple?

3.4k Views Asked by At

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

5

There are 5 best solutions below

0
On BEST ANSWER

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

6
On

Yes, but you need an else statement:

>>> country = 'australia'
>>> A = (
...   'parlament',
...   'queen/king' if not country in ('england', 'sweden') else 'default',
...   'press',
...   'judges'
...      )
>>> print A
('parlament', 'queen/king', 'press', 'judges')

Another example:

>>> country = 'england'
>>> A = (
...   'parlament',
...   'queen/king' if not country in ('england', 'sweden') else 'default',
...   'press',
...   'judges'
...    )
>>> print A
('parlament', 'default', 'press', 'judges')

This is a conditional expression, otherwise known as a ternary conditional operator.

1
On

Yes you can, but for that your ternary condition must be a valid one, i.e you require an else clause too.

Ternary operator in python:

>>> 'x' if False else 'y'
'y'

Your code:

A = (
  'parlament',
  'queen/king' if not country in ('england', 'sweden') else 'foo',
  'press',
  'judges'
   )
1
On

can propose You following

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

this allows You to include or not include elements in result tuple (unlike default value, which will be included if You will not use tuple concatenation.

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

You can use Ternary conditional operator eg:

A= ('a', 'b', 'c' if condition else 'd')