Luis González Luis González - 3 months ago 11x
Python Question

What is the pythonic way for 'do_this() if condition else pass '?

There is exists a way for writing this in a single line?

>> list.append(elem) if condition else pass

I have needed sometimes something like that and I don't know the best way for accomplish it.



if statements are exactly meant for conditionally executing a statement!

if condition:

If you really wanted it all in one line, I suppose you could do:

if condition: list.append(elem)

But this would definitely much less readable and idiomatic!

For your second example (update: it was edited out of the question), Python lets you use a ternary expression anywhere, so you can shorten

list.append(elem) if condition else other_list.append(elem)


(list1 if condition else list2).append(elem)

However, it would be more readable—and thus, again, more idiomatic—to split the above into two statements:

lucky_list = list1 if condition else list2