python "if len(A) is not 0" vs "if A" statements

Viewed 9252

My colleague uses this way in conditions

if len(A) is not 0:
    print('A is not empty')

I prefer this one

if A:
    print('A is not empty')

What is prop-cons arguments?

Her point is that first way is more straight-forward way to show what she exactly wants. My point is that my way is shorter.

Also first way is 2 times faster then my one:

>>> import timeit
>>> timeit.timeit('len(A) is not 0', setup='A=[1,2,3]')
0.048459101999924314
>>> timeit.timeit('bool(A)', setup='A=[1,2,3]')
0.09833707799998592

But

>>> import timeit
>>> timeit.timeit('if len(A) is not 0:\n  pass', setup='A=[1,2,3]')
0.06600062699999398
>>> timeit.timeit('if A:\n  pass', setup='A=[1,2,3]')
0.011816206999810674 

second way 6 times faster! I am confused how if works :-)

4 Answers

PEP 8 style guide is clear about it:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No:  if len(seq):
     if not len(seq):

I would argue that if A = 42, your colleague code would raise an error

object of type 'int' has no len()

while your code would just execute whatever comes after the if.

1.

if len(A) is not 0:
    print('A is not empty')

2.

if A:
    print('A is not empty')

the difference between first way and second way is that you can use len(A) only for structure like list,tuples,dictionary as they support the len() fuction but you can not use the len() fuction for data or like characters, strings, integers(numbers).

for example:

len(123), len(abc), len(123abc) : will raise an error.

but, list = [1,2,3,4,5]

len(list) will not raise an error

if A:
    statement  # this is useful while our only concern is that the variable A has some value or not 

You are not comparing the same thing. If you compare this:

import timeit
print(timeit.timeit('if len(A) is not 0:\n  pass', setup='A=[1,2,3]'))
print(timeit.timeit('if A:\n  pass', setup='A=[1,2,3]'))

You will see that your method is faster. Plus your method is a more pythonic way.

Related