How to use while not in Python

A while not statement in Python loops infinitely while the value of a condition returns false.

 

To demonstrate this, let's count to three with a while not statement. When the condition is equal to three the loop will stop.

 

condition = 0

while not (condition == 3):
   condition = condition + 1
   print(condition)
1
2
3

 

Python while not in

A variation is where not in, which is useful for evaluating if a value is in a list of values.

 

numbers = [0,1,2]
count = 0

while 8 not in numbers:
   if count not in numbers:
       numbers.append(count)
   count = count + 1
   
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8]