N Randhawa
N Randhawa

Reputation: 9491

Simplify if statement python

Is there any Pythonic or compact way to write the following if statement:

if head is None and tail is None:
    print("Test")

Something like:

if (head and tail) is None: 

Upvotes: 2

Views: 5378

Answers (4)

Marcel Wilson
Marcel Wilson

Reputation: 4572

Your code is just about as Pythonic as it can be.

When it comes to these things, The Zen of Python is helpful in remembering that sometimes straightforward is the best option.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
etc...

Upvotes: 2

PM 2Ring
PM 2Ring

Reputation: 55469

if head is None and tail is None:
    print("Test")

is clear and efficient. And if either head or tail can possibly take false-ish values apart from None but you only want "Test" to be printed when they're both None then what you've written is safer than

if not (head or tail):        
    print("Test")

A more compact version (than your code) which is still both safe & efficient is

if head is None is tail:
    print("Test")

head is None is tail is actually equivalent to (head is None) and (None is tail). But I think it's a little less readable than your original version.

BTW, (head and tail) is None is valid Python syntax, but it's not recommended, since it doesn't do what you might at first expect it do:

from itertools import product

print('head, tail, head and tail, result')
for head, tail in product((None, 0, 1), repeat=2):
    a = head and tail
    print('{!s:>4} {!s:>4} {!s:>4} {!s:>5}'.format(head, tail, a, a is None))

output

head, tail, head and tail, result
None None None  True
None    0 None  True
None    1 None  True
   0 None    0 False
   0    0    0 False
   0    1    0 False
   1 None None  True
   1    0    0 False
   1    1    1 False

Upvotes: 2

Kirill Bulygin
Kirill Bulygin

Reputation: 3826

By the way, descriptions like (head and tail) is None are not allowed in programming for the same reason why (a and b) = 0 is not allowed in mathematics (to force each statement to have only one, canonical form; "There should be one obvious way to do each thing" is also an explicit Python motto).

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121196

If both head and tail are custom class instances (like Node() or similar) without a length or boolean value, then just use:

if not (head or tail):

This won't work if ether head or tail could be objects other than None with a false-y value (False, numeric 0, empty containers, etc.).

Otherwise, you are stuck with the explicit tests. There is no "English grammar" shortcut in boolean logic.

Upvotes: 4

Related Questions