What does an 'x = y or z' assignment do in Python?

Why do Python assignments always include or?

We sometimes see examples of this in Python as a substitute for conditional expression with ternary assignments, (in fact, it helped inspire the language to add conditional statements).

x = a or b

Here's an example of a conditional expression that accomplishes the same thing, but with perhaps a bit less mystery.

def my_function(arg_1=None, arg_2=0):
    determination = arg_1 or arg_2 or 'no arguments given!'
    return determination

For example

'' or[] or 'apple'or() or set(['banana'])

returns 'apple,' which is the first element to evaluate to True, and 'apple'.

'' or [] or ()

returns (), even though it evaluates as False.

Although it is less obvious right away than using or, using and for the assignment has historically been used for ternary tasks. That is, prior to the availability of this more straightforward, clearer construction:

a = x
if condition
else y

The equivalent formed with boolean operators was:

a = condition and x or z # don 't do this!
Note: It is important to be cautious while using Boolean expressions for assignment. You should never utilise for assignments because it is quite confusing and prone to mistakes. For assignments, using or will be less appealing to style mavens (than the more verbose ternary, if condition else).

I hope you like this article


28 views0 comments

Recent Posts

See All