Skip to content
Advertisement

Conditionally add items to a list when defining the list?

Is there a way to add items to a list conditionally, when defining the list? Here’s what I mean:

l = [
    Obj(1),
    Obj(2),
    Separator() if USE_SEPARATORS,
    Obj(3),
    Obj(4),
    Obj(5),
    Separator() if USE_SEPARATORS,
    Obj(6)
]

Obviously the above code doesn’t work, but is there a similar way?

Currently I have

l = [item for item in (
        Obj(1),
        Obj(2),
        Separator() if USE_SEPARATORS,
        Obj(3),
        Obj(4),
        Obj(5),
        Separator() if USE_SEPARATORS,
        Obj(6)
) if not isinstance(item, Separator) or USE_SEPARATORS]

But I was wondering if there’s an other way that wouldn’t required looping through the list, since they can be 10 000 items long and the server stops for a quarter second or so when I execute the code. It’s for a first-person shooter game, so quarter second might actually have an effect on someone dying or living.

Advertisement

Answer

Another approach is to use the splat/unpacking operator to expand an element either to the separator or to nothing:

possible_separator = (Separator(),) if USE_SEPARATORS else ()
l = [
    Obj(1),
    Obj(2),
    *possible_separator,
    Obj(3),
    Obj(4),
    Obj(5),
    *possible_separator,
    Obj(6)
]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement