Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know you can do something like this in python:

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

but how would I do something like this?

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

That is, I don't want to substitute the 1 for another number. I want to simply omit it if conditional is false.

like image 489
Caustic Avatar asked Sep 24 '13 18:09

Caustic


3 Answers

Slightly faster than https://stackoverflow.com/a/18988829/1093967 in Python 3.5+ (leveraging additional unpacking generalizations introduced by PEP-448):

>>> timeit("([1, 2, 3] if True else []) + [4, 5, 6]")
0.10665618600614835
>>> timeit("[*([1, 2, 3] if True else []), 4, 5, 6]")
0.08992647400009446
like image 109
deepyaman Avatar answered Oct 18 '22 09:10

deepyaman


Use concatenation:

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

In other words, generate a sublist that either has the optional element in it, or is 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 for more elements too, of course:

x = ([1, 2, 3] if conditional else []) + [4, 5, 6]
like image 38
Martijn Pieters Avatar answered Oct 18 '22 08:10

Martijn Pieters


You can do it with a slice

x = [1, 3, 4][not conditional:]

eg

>>> conditional = False
>>> [1, 3, 4][not conditional:]
[3, 4]
>>> conditional = True
>>> [1, 3, 4][not conditional:]
[1, 3, 4]
like image 26
John La Rooy Avatar answered Oct 18 '22 09:10

John La Rooy