Is there a way to add items to a list conditionally, when defining the list? Here’s what I mean:
JavaScript
x
11
11
1
l = [
2
Obj(1),
3
Obj(2),
4
Separator() if USE_SEPARATORS,
5
Obj(3),
6
Obj(4),
7
Obj(5),
8
Separator() if USE_SEPARATORS,
9
Obj(6)
10
]
11
Obviously the above code doesn’t work, but is there a similar way?
Currently I have
JavaScript
1
11
11
1
l = [item for item in (
2
Obj(1),
3
Obj(2),
4
Separator() if USE_SEPARATORS,
5
Obj(3),
6
Obj(4),
7
Obj(5),
8
Separator() if USE_SEPARATORS,
9
Obj(6)
10
) if not isinstance(item, Separator) or USE_SEPARATORS]
11
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:
JavaScript
1
12
12
1
possible_separator = (Separator(),) if USE_SEPARATORS else ()
2
l = [
3
Obj(1),
4
Obj(2),
5
*possible_separator,
6
Obj(3),
7
Obj(4),
8
Obj(5),
9
*possible_separator,
10
Obj(6)
11
]
12