{"record":{"id":"adbfd5d61dbb8187","repo":"pola-rs/polars","slug":"the-truth-value-of-a-series-is-ambiguous-here-are","errorCode":null,"errorMessage":"the truth value of a Series is ambiguous\n\nHere are some things you might want to try:\n- instead of `if s`, use `if not s.is_empty()`\n- instead of `s1 and s2`, use `s1 & s2`\n- instead of `s1 or s2`, use `s1 | s2`\n- instead of `s in [y, z]`, use `s.is_in([y, z])`\n","messagePattern":"the truth value of a Series is ambiguous\n\nHere are some things you might want to try:\n- instead of `if s`, use `if not s\\.is_empty\\(\\)`\n- instead of `s1 and s2`, use `s1 & s2`\n- instead of `s1 or s2`, use `s1 \\| s2`\n- instead of `s in \\[y, z\\]`, use `s\\.is_in\\(\\[y, z\\]\\)`\n","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":752,"sourceCode":"        Examples\n        --------\n        >>> s = pl.Series(\"a\", [1, 2, 3])\n        >>> s.shape\n        (3,)\n        \"\"\"\n        return (self._s.len(),)\n\n    def __bool__(self) -> NoReturn:\n        msg = (\n            \"the truth value of a Series is ambiguous\"\n            \"\\n\\n\"\n            \"Here are some things you might want to try:\\n\"\n            \"- instead of `if s`, use `if not s.is_empty()`\\n\"\n            \"- instead of `s1 and s2`, use `s1 & s2`\\n\"\n            \"- instead of `s1 or s2`, use `s1 | s2`\\n\"\n            \"- instead of `s in [y, z]`, use `s.is_in([y, z])`\\n\"\n        )\n        raise TypeError(msg)\n\n    def __getstate__(self) -> bytes:\n        return self._s.__getstate__()\n\n    def __setstate__(self, state: bytes) -> None:\n        self._s = Series()._s  # Initialize with a dummy\n        self._s.__setstate__(state)\n\n    def __str__(self) -> str_:\n        s_repr: str = self._s.as_str()\n        return s_repr.replace(\"Series\", f\"{self.__class__.__name__}\", 1)\n\n    def __repr__(self) -> str_:\n        return self.__str__()\n\n    def __len__(self) -> int:\n        return self.len()\n","sourceCodeStart":734,"sourceCodeEnd":770,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/series/series.py#L734-L770","documentation":"Series.__bool__ (py-polars/src/polars/series/series.py:752) deliberately raises TypeError because a Series has no single truth value: it is a collection of many elements, so `if s:` is ambiguous (length? all-true? any-true?). Python calls __bool__ for bool(s), `if s`, and the and/or operators, and polars rejects all of them with an actionable hint message.","triggerScenarios":"if s: ...; bool(s); s1 and s2; s1 or s2; `s in [a, b]` (uses __eq__ then truth evaluation of the result); passing a Series to assert; using a Series where a plain bool is required (e.g. ternary condition).","commonSituations":"Code written for a single scalar value later reused with a Series; wrapping results in assert; `if result:` guards after operations that sometimes return Series. The fix depends on intent: emptiness, all/any, or set membership.","solutions":["Emptiness: if s.is_empty(): ... (or `if not s.is_empty()`)","Elementwise logic: use s1 & s2 (and), s1 | s2 (or), ~s (not); for reduction use s.all() / s.any()","Membership: s.is_in([y, z]) instead of `s in [y, z]`","For tests use assert_series_equal instead of assert"],"exampleFix":"# before\nif s1 and s2: ...\nif s in [\"a\", \"b\"]: ...\n\n# after\nif not (s1 & s2).is_empty(): ...\nmask = s1 & s2  # elementwise 'and'\nif s.is_in([\"a\", \"b\"]).any(): ...","handlingStrategy":"validation","validationCode":"# Decide intent explicitly before branching on a Series:\nif s.is_empty():          # instead of: if not s\n    ...\n\nmask = (s1 > 0) & (s2 > 0)  # instead of: (s1 > 0) and (s2 > 0)\nif mask.any():           # reduction instead of truth of Series\n    ...","typeGuard":"from polars import Series\n\ndef as_bool(x: object) -> bool:\n    \"\"\"Only allow real bools; fail loudly for Series.\"\"\"\n    if isinstance(x, Series):\n        raise TypeError(\"cannot coerce Series to bool; use .any()/.all()/.is_empty()\")\n    return bool(x)","tryCatchPattern":"try:\n    flag = bool(result)  # result is sometimes a Series\nexcept TypeError as e:\n    if \"truth value of a Series is ambiguous\" in str(e):\n        flag = result.any() if hasattr(result, \"any\") else False\n    else:\n        raise","preventionTips":["Never use `if series:` — pick is_empty(), .any(), or .all() per intent","Use & | ~ for elementwise boolean logic; is_in() for membership","In tests use polars.testing.assert_series_equal, never assert series"],"tags":["polars","series","typeerror","boolean-logic","api-misuse"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}