python “if len(A) is not 0” vs “if A” statements

  • A+

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 


>>> 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 :-)


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): 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: