Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Call a Function on a Condition

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.

like image 457
Windstorm1981 Avatar asked Dec 12 '25 06:12

Windstorm1981


2 Answers

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.

like image 65
jpp Avatar answered Dec 13 '25 19:12

jpp


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.

like image 44
onr Avatar answered Dec 13 '25 18:12

onr