Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
borokov@lemmy.world 1 day agoDon’t know how list are implemented in Python. But in the dumb linked list implementation (like C++ std::list), each element has a “next” member that point the the next element. So, to have list length, you have to do (pseudo code, not actual python code):
len = 0 elt = list.fisrt while exist(elt): elt = elt.next len++ return len
Whereas to test if list is empty, you just have to:
return exist(list.first)
riodoro1@lemmy.world 1 day ago
That’s exactly what I was getting at. Getting length of an empty list would not even enter the loop.
ChaoticNeutralCzech@feddit.org 1 day ago
Yes. If it’s empty. But in cases where you need to check, it might as well not be.