Can I optionally include one element in a list without an else statement in python? -


i know can in python:

>>> conditional = false >>> x = [1 if conditional else 2, 3, 4] [ 2, 3, 4 ] 

but how this?

>>> conditional = false >>> x = [1 if conditional, 3, 4] [ 3, 4 ] 

that is, don't want substitute 1 number. want omit if conditional false.

use concatenation:

x = ([1] if conditional else []) + [3, 4] 

in other words, generate sublist either has optional element in it, or empty.

demo:

>>> conditional = false >>> ([1] if conditional else []) + [3, 4] [3, 4] >>> conditional = true >>> ([1] if conditional else []) + [3, 4] [1, 3, 4] 

this concept works more elements too, of course:

x = ([1, 2, 3] if conditional else []) + [4, 5, 6] 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -