Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty list evaluates to False on a while loop in Python

What is process that occurs for a while-loop to evaluate to False on an empty list ?

For instance:

a=[1, 2, 3]
while a:
    a.pop()

Essentially, I want to know which method or attribute of the list object the while-loop is inspecting in order to decide wether to terminate or not.

like image 568
VanillaSpinIce Avatar asked Dec 08 '22 13:12

VanillaSpinIce


2 Answers

Loops and conditionals implicitly use bool on all their conditions. The procedure is documented explicitly in the "Truth Value Testing" section of the docs. For a sequence like a list, this usually ends up being a check of the __len__ method.

bool works like this: first it tries the __bool__ method. If __bool__ is not implemented, it checks if __len__ is nonzero, and if that isn't possible, just returns True.

As with all magic method lookup, Python will only look at the class, never the instance (see Special method lookup). If your question is about how to change the behavior, you will need to subclass. Assigning a single replacement method to an instance dictionary won't work at all.

like image 105
Mad Physicist Avatar answered May 20 '23 13:05

Mad Physicist


Great question! It's inspecting bool(a), which (usually) calls type(a).__bool__(a).

Python implements certain things using "magic methods". Basically, if you've got a data type defined like so:

class MyExampleDataType:
    def __init__(self, val):
        self.val = val

    def __bool__(self):
        return self.val > 20

Then this code will do what it looks like it'll do:

a = MyExampleDataType(5)
b = MyExampleDataType(30)

if a:
    print("Won't print; 5 < 20")
if b:
    print("Will print; 30 > 20")

For more information, see the Python Documentation: 3.3 Special Method Names.

like image 26
wizzwizz4 Avatar answered May 20 '23 13:05

wizzwizz4