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.

Abizern
152k41 gold badges209 silver badges260 bronze badges
asked Jun 21, 2011 at 8:16

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

answered Jun 21, 2011 at 8:20
Sign up to request clarification or add additional context in comments.

Comments

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
answered Jun 21, 2011 at 8:24

Comments

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
answered Jun 21, 2011 at 8:20

Comments

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.

answered Jun 21, 2011 at 8:19

Comments

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.

answered Jun 21, 2011 at 8:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.