10000 Non standard behaviour converting array to bool · Issue #8622 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content
Non standard behaviour converting array to bool #8622
Closed
@mjr129

Description

@mjr129

Description

Normally, to test if an list, array, dictionary, etc. is None or empty in Python I can use:

if not my_list:
    return "The list is empty!"
else:
    return "The list is not empty!"

However, Numpy seems to base this on the lists' content rather than length. Furthermore, it raises an exception if the length is > 1. This:

  • Is confusing
  • Breaks Pythons duck-typing, forcing an expensive recast before I provide Numpy arrays to standard Python functions.
  • Doesn't appear to have a strong use case: the current functionality can be reproduced with a.any or a.all with less ambiguity.

Steps to reproduce

import numpy

bool( [] )    # False
bool( [0] )    # True
bool( [0, 0] )    # True

bool( {} )    # False
bool( {0: 0} )    # True
bool( {0: 0, 1: 0} )    # True

bool( numpy.array( [] ) ) # False
bool( numpy.array( [0] ) ) # False (???)
bool( numpy.array( [0, 1] ) ) # ValueError: The truth value of an array with more than one element is ambiguous.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0