What's the opposite of `x in y` in a list comprehension/generator expression?

An example I came up was something like this:

identified_characters = ["a","c","f","h","l","o"]
word = "alcachofa#"
if any(character in word for character not in identified_characters):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

but the not brings a syntax error, so I was thinking that if there was an out (opposite of in I guess) function theoretically you could change the not in and keep the syntax.

I also thought the logic of the given result should be the opposite of the any function, but looking up I saw that ppl came out that the opposite of any should be not all, in which case wouldn't work here.

Upvotes: 1

Views: 485

Answers (2)

nog642
nog642

Reputation: 619

You can't loop over every possible item not in identified_characters; there are unaccountably many. That doesn't even make sense in concept.

To achieve what you want (checking if there are unidentified characters (characters not in identified_characters) in word), you will have to loop over word, not the complement of identified_characters.

identified_characters = {"a", "c", "f", "h", "l", "o"}

word = "alcachofa#"
if any(character not in identified_characters for character in word):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

Upvotes: 2

fig
fig

Reputation: 374

Instead of using not in the for statement, use it on the character in word part.

identified_characters=["a","c","f","h","l","o"]
word="alcachofa#"
if any(character not in identified_characters for character in word):
    print("there are unidentified characters inside the word")
else:
    print("there aren't unidentified characters inside the word")

For loops can use in but not not in because they have no idea what not in means! For loops are meant to iterate through lists or any iterable and can't iterate through what is not in an iterable as they have no idea what is "not in" the iterable. You can also use not all in the following way:

Upvotes: 1

Related Questions