Storing unique string using if no in == False

Viewed 65

writing a simple code to store unique string into list. However if i use if var in list == False the string output = blank. However if i use If var not in list, I gotten the desired output.

please advise why if var in list == False does not work here.

bank = list()

while True:
      word = input('Enter a word,type"done"to finish')

      if word == 'done': break

      if word in bank == False: # this code does't work as intended
            bank.append(word)

bank.sort()
print(bank)
3 Answers

Its a bit subtle but its because of Comparison chaining. Comparitors < | > | == | >= | <= | != | is [not] | [not] in have equal prescience and are compared left to right. In addition, chaining of the operations is the same as adding an "and". The familiar example is:

x < y <= z is equivalent to x < y and y <= z.

The same holds for in. Your expression is the same as

if (word in bank) and (bank == False):
    ....

Your working example if word in bank: is the canonical way of writing the expression... no need to make it complicated!

@tdelaney gave the correct above. Here is how you would write it:

if word not in bank:
  bank.append()

Or even better use a set instead of a list.

bank = set()
while True:
  word = input('Enter a word,type"done"to finish')
  if word == 'done':
    break
  bank.add(word)

bank = list(bank)
bank.sort()
print(bank);

Your code doesn't work because it represents it like:

if word in (bank == False):

It's like the order of operations in math, so it takes it first processes whether bank is False, not processing first whether word is in bank, so if you use parenthesis, it would work:

if (word in bank) == False:

If you change it to the above ^, it would work.

But of course it's more recommended if you use:

if word not in bank:
Related