I am writing a list comprehension in Python:
[2 * x if x > 2 else add_nothing_to_list for x in some_list]
I need the "add_nothing_to_list" part (the else part of the logic) to literally be nothing.
Does Python have a way to do this? In particular, is there a way to say a.append(nothing) which would leave a unchanged. This can be a useful feature to write generalized code.
Just move the condition to the last
[2 * x for x in some_list if x > 2]
Quoting the List Comprehension documentation,
A list comprehension consists of brackets containing an expression followed by a
forclause, then zero or morefororifclauses. The result will be a new list resulting from evaluating the expression in the context of theforandifclauses which follow it.
In this case, the expression is 2 * x and then a for statement, for x in some_list, followed by an if statement, if x > 2.
This comprehension can be understood, like this
result = []
for x in some_list:
if x > 2:
result.append(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With