Search code examples
pythonarrayswhile-loopboolean-expression

run while loop while a boolean condition is true


I have a 2D numpy array (400x400) and while there are zeros in this array I want to run a while loop until after a few iterations they are all removed. So in the while block I remove some of the zeros in every iteration. From here I have the code snipped to check if there are still zeros in my array:

check = 0 in array

This returns either a 'True' or a 'False' and is working. Now I want to use this in the beginning of the while-loop and I expected it to work like the following:

while 0 in array == True:
    'do sth.'

Instead I get the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I can make a workaround where in the end of every while-loop I write the result of 'check = 0 in array' into another variable and check this variable in the beginning of the while loop, but I think there should be a better way.


Solution

  • Python parses this as

    while 0 in (array==True):
    

    where of course you mean

    while (0 in array) == True:
    

    which however of course is better written

    while 0 in array:
    

    Python's flow-control conditionals already implicitly convert every expression into a "truthiness" value which is either True or False. See further What is Truthy and Falsy? How is it different from True and False?