I could have tripped, knocked over my keyboard, cried for 13 straight minutes on the floor, picked my keyboard back up, accidentally hit the enter key making a graph and it would have made more sense than this thing.
I haven't read the article. But I'd assume this is for the same reason that not not string is faster than bool(string). Which is to say that it has to do with having to look up a global function rather than a known keyword.
Isn't it because list is linked list, so to get the Len it has to iterate over the whole list whereas to get emptyness it just have to check if there is a 1st element ?
I write a lot of Python. I hate it when people use "X is more pythonic" as some kind of argument for what is a better solution to a problem. I also have a hang up with people acting like python has any form of type safety, instead of just embracing duck typing.This lands us at the following:
The article states that "you can check a list for emptiness in two ways: if not mylist or if len(mylist) == 0". Already here, a fundamental mistake has been made: You don't know (and shouldn't care) whether mylist is a list. These two checks are not different ways of doing the same thing, but two different checks altogether. The first checks whether the object is "falsey" and the second checks whether the object has a well defined length that is zero. These are two completely different checks, which often (but far from always) overlap. Embrace the duck type- type safe python is a myth.
Yea and then you use "not" with a variable name that does not make it obvious that it is a list and another person who reads the code thinks it is a bool. Hell a couple of months later you yourself wont even understand that it is a list. Moreover "not" will not throw an error if you don't use an sequence/collection there as you should but len will.
You should not sacrifice code readability and safety for over optimization, this is phyton after all I don't think list lengths will be your bottle neck.
As a Perl fossil I recognise this syntax as equivalent to if(not @myarray) which does the same thing. And here I was thinking Guido had deliberately aimed to avoid Perlisms in Python.
That said, the Perlism in question is the right* way to do it in Perl. The length operator does not do the expected thing on an array variable. (You get the length of the stringified length of the array. And a warning if those are enabled.)
* You can start a fight with modern Perl hackers with whether unless(@myarray) is better or just plain wrong, even if it works and is equivalent.