Default argument and Ternary operators in Python

The objects like list, dict are mutable. A mutable object can change its state or contents, so whenever we use these types of mutable objects as default argument in Python functions, and execute or call the function multiple times it gives unnecessary output for each function call.

The example shown below is to return the list of even numbers, using the mutable list as default argument (even_list = []).


As you can see, for the first function call, it returns exactly what we expected. On the second and all subsequent function calls, the same list is used in each call.

Now what we can do for avoiding this type of result is, we can set the mutable default argument as None and assign the mutable data within the function using specific condition.


Ternary operator provides short and concise way to write the conditional statements and allows to evaluate and test the condition in a single line of code.


True_value if condition else false_value


Like as ternary operator using if..else we can also implement the same using list, tuple, dictionary and lambda.

Using List


[false_value, true_value][condition]

Using Dictionary


{True: true_value, False: false_value} [condition]

Using Lambda


(lambda: false_value, lambda: true_value) [condition]()

Popular Posts

Spread the knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *