3

I was wondering if there is a concise way to call a function on a condition.

I have this:

if list_1 != []:
    some_dataframe_df = myfunction()

I'm wondering if it is possible to this in a ternary operator or something similiar.

If I do

(some_dataframe_df = myfunction()) if list_1 != [] else pass

It doesn't work.

2
  • 6
    That first bit of code is fine. Trying to reduce it further will like just convolute the point of it. Smaller isn't always better. Commented Nov 9, 2018 at 16:03
  • 1
    Also, instead of list != [], it's a better pattern to use if not list_1:. This will evaluate to true/false if "iterable" is empty. That allows for the correct check for all zero-lenth iterables, even it's a different type of iterable (tuble, dict keys, etc) Commented Nov 9, 2018 at 16:46

3 Answers 3

4

Your code is fine. The only change I suggest is to use the inherent Truthness of non-empty lists:

if list_1:
    some_dataframe_df = myfunction()

If you wish to use a ternary statement it would be written as:

some_dataframe_df = myfunction() if list_1 else some_dataframe_df

However, this is neither succinct nor readable.

Sign up to request clarification or add additional context in comments.

Comments

2

In ternary operator, the conditionals are an expression, not a statement. Therefore, you can not use pass and normal if statement that you have used is correct.

Comments

1

Using pass seems like a bad idea in a ternary operator, especially since you can inline a single-statement if.

If you are not worried about your list being None, you can shorten the test to just use the boolean value of the list itself. This has the advantage that it will allow any normal sequence, not just lists.

All in all, you could do something like:

if list_1: some_dataframe_df = myfunction()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.