lamwaiman1988
lamwaiman1988

Reputation: 3742

What is this code doing?

>>> 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.

Upvotes: 3

Views: 538

Answers (5)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

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

Upvotes: 2

anton.burger
anton.burger

Reputation: 5706

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

Upvotes: 4

Dawid
Dawid

Reputation: 654

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.

Upvotes: 1

ICR
ICR

Reputation: 14162

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

Upvotes: 7

David Heffernan
David Heffernan

Reputation: 612884

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.

Upvotes: 1

Related Questions