3
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

This from the python tutorial of this page, I don't understand the 2nd line.

5 Answers 5

7

The python or operator can be defined as [1]:

x or y : if x is false, then y, else x

When you do string1 or string2, string1 is an empty string, which Python translates as False (side node: some programming languages do this, others don't), so by the definition above it evaluates to the value of string2. When it then does (result of 'string1 or string2') or string3, string2 is not an empty string, and so does not equate to False, and so it evaluates to string2.

[1] http://docs.python.org/release/2.5.2/lib/boolean.html

4

Demonstrating a) operator short-circuiting and b) the fact that, in Python, logical operators can take and return non-bool values:

string1 or string2 or string3 # is the same as
(string1 or string2) or string3
# string1 or string2 is '' or 'Trondheim', and as
# '' is logically False, this results in 'Trondheim'
# 'Trondheim' or string3 is short-circuited and never evaluated,
# because a non-empty string is logically True
2

It simply returns you the first non empty string 'Trondheim' and is the same as:

non_null = (string1 or string2) or string3

Or:

if not string1:
    string3 if not string2 else string2
else:
    string1
1

If uses short circuit boolean evaluation to find the first non-null string in the list. For strings, the empty string '' evaluates to False and everything other string is regarded as a True value.

Sections 5.1 and 5.2 from the documentation tell you all you need to know to understand this.

In particular:

x or y       if x is false, then y, else x

This is a short-circuit operator, so it only evaluates the second argument if the first one is False.

1

It just checks which string is not null and passes it to a non_null variable. string1 is empty, so the string2 can be used.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.