1

Suppose I have a list Q. In the following code:

while Q:
    do_something()
    Q.pop()

in the while Q statement, what method of the list Q is invoked? Is it the __len__ method?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Victor Hugo
  • 181
  • 9
  • Why would it be `len`? And `len` isn't a method of the list anyways. `__len__` would be the method. – Carcigenicate Apr 30 '17 at 16:22
  • @Carcigenicate it's __ len __ actually. The editor converted the "__" to bold. Thanks for the warning – Victor Hugo Apr 30 '17 at 16:24
  • Ahh. It's a good idea to wrap small code bits in backticks to prevent markup attempts. But again, why mention `__len__`? It may be called behind the scenes, but in this code snippet, `pop` is the method being called. – Carcigenicate Apr 30 '17 at 16:26
  • @Carcigenicate He's asking how `Q` is treated as a Boolean value, which could conceivably involve `__len__` being called. – chepner Apr 30 '17 at 16:27

3 Answers3

3

In Python 3.x, it's __bool__ or __len__:

object.__bool__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.

In 2.x it was named __nonzero__; see what's new in 3.0.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

From python's documentation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • (...)
  • any empty sequence, for example, '', (), [].
  • (...)
  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False. [Additional information on these special methods may be found in the Python Reference Manual (Basic customization).]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

silel
  • 567
  • 2
  • 10
0

Yes, __len__ does get called in this case.

Let's see this code snippet:

class clist(list):

    def __len__(self):
        print "Called"

Q = clist([1,2,3,4])

while Q:
    break

Output:

Called
Traceback (most recent call last):
  File "a.py", line 10, in <module>
    while Q:
TypeError: an integer is required

But, if I remove the method,

class clist(list):
    pass

Q = clist([1,2,3,4])

while Q:
    break    

the code will run just fine, but won't print anything.

So yes, __len__ does get called.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57