python - How can I add nothing to the list in list comprehension? -
i writing list comprehension in python:
[2 * x if x > 2 else add_nothing_to_list x in some_list]
i need "add_nothing_to_list" part (the else part of logic) literally nothing.
does python have way this? in particular, there way a.append(nothing)
leave a
unchanged. can useful feature write generalized code.
just move condition last
[2 * x x in some_list if x > 2]
quoting list comprehension documentation,
a list comprehension consists of brackets containing expression followed
for
clause, 0 or morefor
orif
clauses. result new list resulting evaluating expression in context offor
,if
clauses follow it.
in case, expression 2 * x
, for
statement, for x in some_list
, followed if
statement, if x > 2
.
this comprehension can understood, this
result = [] x in some_list: if x > 2: result.append(x)
Comments
Post a Comment