Python / Core Python Fundamentals Interview Questions
How does Python determine whether a custom object is truthy or falsy?
Every Python object has a boolean value. In a boolean context (an if condition, a while condition, or passed to bool()), Python calls the object's __bool__ method first. If that is not defined, it falls back to __len__ and returns False if __len__ returns 0. If neither is defined, the object is always truthy.
class Queue:
def __init__(self):
self._data = []
def enqueue(self, item):
self._data.append(item)
def __len__(self):
return len(self._data)
def __bool__(self):
return len(self._data) > 0 # explicit
q = Queue()
if not q:
print('Queue is empty') # printed — __bool__ returns False
q.enqueue('item')
if q:
print('Queue has items') # printed — __bool__ returns TrueThe built-in falsy values to memorise: None, False, 0, 0.0, 0j (complex zero), '' (empty string), b'' (empty bytes), [], (), {}, set(), and any object whose __bool__ returns False or whose __len__ returns 0.
Practical impact: you can write Pythonic guards like if items:, while queue:, and return value or default instead of verbose length checks. The short-circuit operators and and or return one of their operands, not necessarily a bool: 'alice' or 'default' returns 'alice'; '' or 'default' returns 'default'.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
