- Оператор Not In в Python
- Что такое оператор Not In в Python?
- Код Python для оператора not in
- Работа с операторами «in» и «not in» в словарях
- Python “in” and “not in” Membership Operators: Examples and Usage
- Python “in” Operator
- Python “not in” Operator
- Using the “in” and “not in” Operators in Python Dictionaries
- Conclusion
- Reference
- Python “in” and “not in” Operators
- The ‘in’ Operator in Python
- The “not in” Operator in Python
- When Use the ‘in’ Operator in Python
- Examples
- Check If a Substring Exists in a String
- Check If a Key Exists in a Dictionary
- Check If a Value Exists in a List
- Conclusion
Оператор Not In в Python
Чтобы проверить, отсутствует ли какой-либо элемент в последовательности, списке, строке, кортеже или наборе, используйте оператор not in. Оператор not in является полной противоположностью оператора in.
Оператор in в Python проверяет, является ли указанное значение составным элементом последовательности.
Что такое оператор Not In в Python?
Not in — это встроенный оператор Python, который проверяет наличие заданного значения внутри заданной последовательности, но его значения противоположны значениям оператора in. Оператор not-in возвращает логическое значение в качестве вывода. Он возвращает либо True, либо False.
Рассмотрим пример кода с оператором Not in в Python.
Код Python для оператора not in
Когда вы используете оператор not in в условии, оператор возвращает логический результат, оценивающий True или False. В нашем примере сначала мы проверяем элемент из списка. Он возвращает False, потому что 19 находится в listA.
stringA содержит «is» в качестве подстроки, и поэтому возвращается False. Когда указанное значение находится внутри последовательности, оператор возвращает True. В то время как, когда он не найден, мы получаем False.
Работа с операторами «in» и «not in» в словарях
Словари не являются последовательностями, потому что они индексируются на основе ключей. Посмотрим, как работать с оператором not in в словарях.
Попробуем разобраться на примере.
Python “in” and “not in” Membership Operators: Examples and Usage
Python has many built-in operators to perform various operations, among them membership operators “in” and “not in” are used to check if something specific is present in iterable or not. Python uses these operators frequently to make search operations easier and more efficient.
This tutorial will introduce you to the “in” and “not in” membership operators and give you several examples so that you can easily implement them in your Python program.
Python “in” Operator
Python “in” operator is used to check whether a specified value is a constituent element of a sequence like string, array, list, tuple, etc.
When used in a condition, the statement returns a Boolean result evaluating either True or False. When the specified value is found inside the sequence, the statement returns True. Whereas when it is not found, we get a False.
Now let us take an example to get a better understanding of the working of “in” operator.
#in operator working list1= [1,2,3,4,5] string1= "My name is AskPython" tuple1=(11,22,33,44) print(5 in list1) #True print("is" in string1) #True print(88 in tuple1) #False
Explanation:
- Here we have initialised a list of integers list1 , a string string1 and a tuple tuple1 with some values. Then we use the ‘in’ operator to check whether a value is a part of the above sequences or not.
- In the output, the integer 5 in list1 evaluates into a True, which signifies that the value 5 is found inside the list in Python.
- Similarly, using the “in” operator we also confirm the presence of the string “is” in string1 .
- But for the last case, the condition results in a False since 88 does not exist inside the sequence tuple1 .
Python “not in” Operator
The “not in” operator in Python works exactly the opposite way as the “in” operator. It also checks the presence of a specified value inside a given sequence but its return values are totally opposite to that of the “in” operator.
When used in a condition with the specified value present inside the sequence, the statement returns False. Whereas when it is not, we get a True.
Let us take the previous example, just replacing “in” operator with the “not in”.
#not in operator working list1= [1,2,3,4,5] string1= "My name is AskPython" tuple1=(11,22,33,44) print(5 not in list1) #False print("is" not in string1) #False print(88 not in tuple1) #True
As expected, the resultant output is the exact opposite of what we got earlier using the “in” operator.
Using the “in” and “not in” Operators in Python Dictionaries
Previously we discussed the working of the “in” and “not in” operators on different types of sequences. But dictionaries are not a sequence, they are not organized in the order of lists and tuples. Instead, dictionaries are indexed on the basis of keys., i.e., dictionaries use key-value pairs to store and fetch data.
So do the above operators work on dictionaries? And if they do, how do they evaluate the condition?
Let us try to understand with an example.
#in and not in operator working on Dictionary dict1 = print("one" in dict1) print("one" not in dict1) print(3 in dict1) print(3 not in dict1) print(5 in dict1) print(5 not in dict1)
Explanation:
- Here we have initialised a dictionary dict1 with a certain set of keys and corresponding values.
- In the output, “one” in dict1 evaluates into a False. Whereas, 3 in dict1 gives us True.
- Meaning that the “in” operator looks for the element among the dictionary keys, not the values. Hence, similarly, the last statement 5 in dict1 also results in a False as it is not a key in the dictionary.
Here the “not in” operator also evaluates in the same way.
Conclusion
Let’s summarize what we’ve learned. In the Python programming language, there are two membership operators “in” and “not in” that can be used when you want to check whether a value or item is present in an iterator. “in” returns True if it is present and if it is not present it returns False, while “not in” is just the opposite, it returns False if it is present, and returns True if not present in a specific sequence. Hope you have successfully learned about “in” and “not in” operators through this tutorial.
Reference
Python “in” and “not in” Operators
In Python, you can use the in operator to check if a value exists in a group of values.
>>> "Alice" in ["Alice", "Bob", "Charlie"] True >>> "H" in "Hello world" True
Similarly, you can check if a value is not in a collection with not in operation (combining the not operator and the in operator):
>>> "David" not in ["Alice", "Bob", "Charlie"] True
The ‘in’ Operator in Python
The in operator works with iterable types, such as lists or strings, in Python. It is used to check if an element is found in the iterable. The in operator returns True if an element is found. It returns False if not.
For example, let’s check if “Charlie” is in a list of names:
>>> names = ["Alice", "Bob", "Charlie"] >>> if "Charlie" in names: . print("Charlie found") . Charlie found
The “not in” Operator in Python
Another common way to use the in operator is to check if a value is not in a group.
To do this, you can negate the in operator with the not operator to give rise to the not in operator.
For example, let’s check if there are no “s” letters in a word:
>>> word = "Hello world" >>> if "s" not in word: . print("No 's' letters found!") . No 's' letters found!
When Use the ‘in’ Operator in Python
Use the in operator whenever you want to check if an iterable object contains a value.
Commonly, you see the in operator combined with an if operator.
Examples
Let’s see some common example use cases for the in operator in Python.
Check If a Substring Exists in a String
As you learned, you can use the in operator with iterables in Python. A Python string is an iterable object. This means you can use the in operator on a string as well.
When using the in operator on a string, you can check if:
For example, let’s see if “Hello” exists in “Hello world”:
>>> "Hello" in "Hello world" True
Check If a Key Exists in a Dictionary
In Python, a dictionary is an indexed collection of key-value pairs unlike lists or strings for example.
As you may know, you can access key-value pairs in the dictionary using keys. So it is the key that gives you access to the dictionary. Similarly, to check if a key-value pair exists in a dictionary, you need to check if the key exists.
This can be useful if you want to safely access a dictionary with the square brackets operator:
>>> data = >>> if "age" in data: . print(f"He is years old.") . He is 30 years old.
If a key-value pair does not exist in the dictionary and you try to access it this way, you would see an error.
>>> data = >>> print(f"He's nickname is ") Traceback (most recent call last): File "", line 1, in KeyError: 'nickname'
So you should always make sure the key-value pair exists before accessing it with the square brackets operator.
Check If a Value Exists in a List
A really common way to use the in operator is to check if a value exists in a list.
For example, let’s see if a specific name exists in a list of names:
>>> students = ["Alice", "Bob", "Charlie"] >>> "Charlie" in students True
Conclusion
Today you learned how to use the in operator to check if a value exists in an iterable in Python.
To recap, the in operator works with any iterable types. You can use it to check if an iterable has a specific value. When you want to check if a value does not exist, just chain the in operator with a not operator to form a not in operator.