Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add nothing to the list in list comprehension?

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.

like image 888
jesperk.eth Avatar asked Mar 21 '15 06:03

jesperk.eth


1 Answers

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 for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses 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)
like image 157
thefourtheye Avatar answered Sep 19 '22 17:09

thefourtheye