3

Say I have a list x = ['a','b','c'] to conditionally add a term to this you could do:

if conditional:
    x.append('d')

But I can't do this for a tuple (x = ('a','b','c'))

For both cases is there a 'clean' way of conditional-alising items in a definition. Pseudo code:

X = (
    'a',
    'b',
    'c',
    'd' if Y,
    'e' if Z,
)

The use case for this is a Django INSTALLED_APPS tuple and urlpatterns list.

6 Answers 6

4

You can just concatenate another tuple to the end.

x = ('a','b','c')
if Y:
    x += ('d',)
if Z:
    x += ('e',)
print(x)
3

One way to do it - useful if you're going to be generating the contents of the tuple a lot - is with a generator:

def gen_X():
    yield 'a'
    yield 'b'
    yield 'c'
    if Y:
        yield 'd'
    if Z:
        yield 'e'

Then make a tuple from the generator results:

X = tuple(gen_X())

With a slightly modified version you can also supply the arguments which determine what the generator will produce:

def gen_X(Y = True, Z = True):
    yield 'a'
    yield 'b'
    yield 'c'
    if Y:
        yield 'd'
    if Z:
        yield 'e'

One nice thing about doing it with a generator is that you don't have to keep multiple sets of the tuple in memory - both the contents and the logic are contained in the generator. So you can be simultaneously iterating through lots of different versions of the same data, but it's all contained in only one location and generated on the fly as you need it.

1
  • I like this method, the cleanest one so far
    – wjdp
    Commented Jul 7, 2015 at 0:40
1

Another way is to make a list, then convert the list to a tuple by calling tuple(lst).

1

Python does not provide this kind of syntactic sugar. The easiest way to solve your problem is to use a list. Then you can use my_list.append(), and finally, when you need a tuple, make a tuple out of it: tuple(my_list). (INSTALLED_APPS = tuple(my_list))

0

One solution would be to concatenate tuples.

x = ('a', 'b', 'c') + (('d',) if Y else ()) + (('e',) if Z else ())

One benefit of doing it this way is it's an expression thus usable inside a lambda.

0

You can do something like this using a generator expression:

truth_table = {'a': True, 'b': True, 'c': True, 'd': Y, 'e': Z}
X = tuple(k for k,v in sorted(truth_table.items()) if v)

...or in one line:

X = tuple(k for k,v in sorted({'a': True, 'b': True, 'c': True, 'd': Y, 'e': Z}.items()) if v)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.