Luis González Luis González - 1 year ago 76
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.


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download