Conventions for defining a tuple / list

Let's say I have a list x = ['a','b','c']

to conditionally add a term to it:

if conditional:
    x.append('d')

      

But I cannot do it for tuple ( x = ('a','b','c')

)

In both cases, there is a "clean" way of contingent alimony in the definition. Pseudocode:

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

      

In this case, the Django INSTALLED_APPS list of tuples and the URL list are used.

+3


source to share


6 answers


One way to do this - useful if you're going to generate content a tuple

lot - with a generator:

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

      

Then make tuple

from the generator results:

X = tuple(gen_X())

      



With a slightly modified version, you can also specify arguments that determine what the generator generates:

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

      

The nicest thing to do with a generator is that you don't need to store multiple sets of tuples in memory - the content and logic is contained in the generator. This way, you can iterate through many different versions of the same data at the same time, but it's all contained in only one place and generated on the fly as needed.

+3


source


You can just concatenate another tuple to the end.



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

      

+4


source


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

.

+1


source


Python does not provide such 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 motorcade, make of it a tuple: tuple(my_list)

. ( INSTALLED_APPS = tuple(my_list)

)

+1


source


One solution would be to concatenate the tuples.

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

      

One of the advantages of this way is that this expression is used inside a lambda.

0


source


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)

      

0


source







All Articles