Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pep8

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

like image 277
vladimirfol Avatar asked Jan 09 '19 10:01

vladimirfol


People also ask

What is the purpose of the statement if Len Stack == 0?

Solution 3: Using len() And given the length of an empty list is 0 it can be used to check if a list is empty in Python.

Does length python start at 0?

Finding the Index of the Last Item of a Sequence To display the last number in the list, you use len(numbers) and subtract 1 from it since the first index of the list is 0 . Indexing in Python allows you to use the index -1 to obtain the last item in a list.

What does Len 1 mean in Python?

len(A)-1 actually is the index of the last element in list A . As in python (and almost all programming languages), array indexes start from 0, so an array with n elements has index of 0, 1, 2, ..., n-1 . Follow this answer to receive notifications. answered May 10, 2018 at 12:06. BookSword.

Why isn't Len a method in Python?

Python has first-class functions, so len is actually an object. Ruby, on the other hand, doesn't have first class functions. So the len function object has it's own methods that you can inspect by running dir(len) .


2 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):
like image 51
Mikhail Gerasimov Avatar answered Sep 23 '22 02:09

Mikhail Gerasimov


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.

like image 27
Statistic Dean Avatar answered Sep 24 '22 02:09

Statistic Dean