Python bool(): Convert Values to Boolean — Syntax, Truthiness Rules, Custom Objects, Empty Containers, Pitfalls, and Practical Examples > dev

Skip to content
Entire search within the site

dev

Python Python bool(): Convert Values to Boolean — Syntax, Truthiness Rules, C…

page info

profile_image
Author Goposu
comment 0co View 11hit Creation date 25-10-11 01:40

본문

Python bool(): Convert Values to Boolean — Syntax, Truthiness Rules, Custom Objects, Empty Containers, Pitfalls, and Practical Examples

Python bool(): Convert a value to True or False

The built-in bool() function converts a value to its boolean representation. In Python, “truthiness” is determined by type-specific rules: some values are considered falsy, while most others are truthy. Understanding these rules helps you write robust validation, control flow, and data-cleaning logic.

Syntax

bool(x)

Parameter: Any object (x) implementing boolean semantics via __bool__() or __len__().

Returns: True or False based on x’s truthiness. If x is omitted, bool() returns False only for bool() on empty or falsy values; note that calling bool() with no argument is invalid.

Truthiness rules

  • Falsy: False, None, numeric zero (0, 0.0, 0j), empty containers ([], (), {}, set(), "", range(0)), and objects whose __bool__() returns False or __len__() returns 0.
  • Truthy: All other values, including non-zero numbers, non-empty strings, and non-empty containers.

Quick examples

print(bool(1))         # True
print(bool(0))         # False
print(bool("hello"))   # True
print(bool(""))        # False
print(bool([1, 2]))    # True
print(bool([]))        # False
print(bool(None))      # False
print(bool(True))      # True
print(bool(False))     # False

Custom objects

Define truthiness by implementing __bool__(). If absent, Python falls back to __len__() and considers len(obj) == 0 as falsy.

class NonEmptyIfPositive:
    def __init__(self, n):
      self.n = n
    def __bool__(self):
      return self.n > 0

x = NonEmptyIfPositive(3)
y = NonEmptyIfPositive(0)
print(bool(x))  # True
print(bool(y))  # False

Common use cases

  • Input validation: Check presence of values before processing.
  • Control flow: Use truthy/falsy conditions in if statements.
  • Data cleaning: Filter out empty records or zero measurements.
records = ["a", "", "b"]
present = [r for r in records if bool(r)]  # ["a", "b"]

Pitfalls and caveats

  • Whitespace strings: " " (space) is non-empty and thus truthy; trim before checks if necessary.
  • NumPy arrays: bool(np.array([1, 2])) raises ValueError due to ambiguous truth value; use arr.any() or arr.all().
  • Custom types: Poorly defined __bool__() can mislead logic; keep semantics consistent and predictable.
  • Chained conditions: Remember that and/or return operands, not strictly booleans; wrap with bool() if you require True/False.
# Whitespace is truthy
print(bool(" "))  # True

# and/or return operands
val = "" or "fallback"
print(val)        # "fallback"
print(bool(val))  # True

Performance notes

  • Built-in speed: bool() is implemented in C; conversions are fast.
  • Lazy evaluation in conditions: Prefer generator-based checks with any()/all() to avoid building temporary lists.
  • Container checks: For lists, sets, dicts, use the container directly in boolean context (if items:)—it’s clear and efficient.

Comparison with any() and all()

  • bool(x): Converts a single object to True/False based on its truthiness.
  • any(iterable): True if at least one element is truthy; empty iterable yields False.
  • all(iterable): True only if every element is truthy; empty iterable yields True.
vals = [0, "", None, "x"]
print(bool(vals))   # True (non-empty list)
print(any(vals))    # True ("x" is truthy)
print(all(vals))    # False (0, "", None are falsy)

FAQ

Is bool a type?
Yes. bool is a subclass of int with values True and False (which behave like 1 and 0 in arithmetic).
How do I check if a container is non-empty?
Use it directly in a condition: if items:. This is equivalent to if bool(items): and checks len(items).
Why does bool("False") return True?
Because "False" is a non-empty string. Parse semantics explicitly if you need textual truth values.

Related keywords

Python bool, truthiness, falsy values, empty containers, __bool__, __len__, any vs all, boolean context, validation

추천0 비추천0

comment list

There are no registered comments.

Total 19건 1 page

search

memberlogin

join

Copyright © https://goposu.com All rights reserved.