Search code examples
pythonlist-comprehensionanyin-operatorgenerator-expression

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.


Solution

  • 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")