Python in Keyword
The in keyword is used to check if a value is present in a sequence (list, range, string etc.).
The in keyword is also used to iterate through a sequence in a for loop:
Example
Loop through a list and print the items:
for x in fruits:
print(x)
COLOR PICKER
Get certified
by completing
a course today!
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Операторы в Python
Операторы — специальные символы, которые выполняют арифметические и логические вычисления. Значения, на которые действует оператор, называются операндами.
Здесь оператор + выполняет сложение, 2 и 3 — операнды, а 5 — вывод операции.
Арифметические операторы
Арифметические операторы используются для выполнения математических операций — сложения, вычитания, умножения и т. д.
Оператор
Действие
Пример
Сложение двух операндов или унарный плюс
Вычитание правого оператора из левого или унарный минус
Умножение двух операндов
Деление левого операнда на правый (результат всегда типа float)
Остаток от деления левого операнда на правый
x % y (остаток от x / y)
Деление с округлением — деление, результат которого корректируется в меньшую сторону
Показатель степени — левый операнд возводится в значение правого операнда
Вывод:
Операторы сравнения
Операторы сравнения используются для сравнения значений, они возвращают True или False в зависимости от условия.
Оператор
Действие
Пример
Больше чем: True, если левый операнд больше правого
Меньше чем: True, если левый операнд меньше правого
Равно: True, если операнды равны между собой
Не равно: True, если операнды не равны между собой
Больше или равно: True, если левый операнд больше или равен правому
Меньше или равно: True, если левый операнд меньше или равен правому
Вывод:
Логические операторы
Операторы and , or , not — логические.
Оператор
Действие
Пример
True, если значения обоих операндов True
True, если значение одного из операндов True
True, если значение операнда False (дополняет значение операнда)
Вывод:
Побитовые операторы
Побитовые операторы работают с операндами как со строками из 0 и 1. Они действуют бит за битом, как и говорит название.
Например, 2 в двоичной системе счисления — 10 , а 7 — 111 .
В таблице ниже: x = 10 ( 00001010 в двоичной системе счисления) и y = 4 ( 00000100 в двоичной системе счисления)
Оператор
Действие
Пример
x & y = 0 ( 00000000 )
x | y = 14 ( 00001110 )
x = -11 ( 11110101 )
x ^ y = 14 ( 00001110 )
Побитовый сдвиг вправо
x >> 2 = 2 ( 00000010 )
Побитовый сдвиг влево
x << 2 = 40 ( 00101000 )
Операторы присваивания
Операторы присваивания используются для назначения переменной некоторого значения.
a = 5 — простой оператор присваивания, который приравнивает значение 5 справа переменной а слева.
В Python множество составных операторов, подобных a += 5 — он прибавляет 5 к переменной a и позже присваивает ей получившееся значение. Этот оператор равносилен записи a = a + 5 .
Оператор
Пример
Эквивалентно
Особые операторы
В Python есть особые типы операторов: операторы тождественности и принадлежности.
Операторы тождественности
is и is not — операторы тождественности в Python. Они проверяют, находятся ли два значения (или две переменные) по одному адресу в памяти. То, что две переменные равны еще не значит, что они идентичны.
Оператор
Действие
Пример
True, если операнды идентичны (указывают на один объект)
True, если операнды не идентичны (не указывают на один объект)
Вывод:
Мы видим, что x1 и y1 — целочисленные переменные с одинаковыми значениями, поэтому они равны и идентичны. То же с x2 и y2 (строки).
Но x3 и y3 — списки. Они равны, но не идентичны, поскольку интерпретатор кладет их в разные места в памяти, хоть эти списки и равны.
Операторы принадлежности
in и not in — операторы принадлежности в Python. Они проверяют, есть ли значение или переменная в последовательности (строке, списке, кортеже, множестве или словаре). Иначе говоря, проверяют вхождение элемента в коллекцию. В словаре можно проверить только присутствие ключа, не значения.
Оператор
Действие
Пример
True, если значение или переменная есть в последовательности
True, если значения или переменной нет в последовательности
Вывод:
‘П’ есть в x , а вот строки ‘привет’ в x нет (помните: Python чувствителен к регистру). Таким же образом образом 1 — ключ, а ‘a’ — значение в словаре y , поэтому вывод ‘б’ in y — False .
Python's "in" and "not in" Operators: Check for Membership
Python’s in and not in operators allow you to quickly determine if a given value is or isn’t part of a collection of values. This type of check is common in programming, and it’s generally known as a membership test in Python. Therefore, these operators are known as membership operators.
In this tutorial, you’ll learn how to:
- Perform membership tests using the in and not in operators
- Use in and not in with different data types
- Work with operator.contains() , the equivalent function to the in operator
- Provide support for in and not in in your own classes
To get the most out of this tutorial, you’ll need basic knowledge of Python, including built-in data types, such as lists, tuples, ranges, strings, sets, and dictionaries. You’ll also need to know about Python generators, comprehensions, and classes.
Source Code: Click here to download the free source code that you’ll use to perform membership tests in Python with in and not in .
Getting Started With Membership Tests in Python
Sometimes you need to find out whether a value is present in a collection of values or not. In other words, you need to check if a given value is or is not a member of a collection of values. This kind of check is commonly known as a membership test.
Arguably, the natural way to perform this kind of check is to iterate over the values and compare them with the target value. You can do this with the help of a for loop and a conditional statement.
Consider the following is_member() function:
This function takes two arguments, the target value and a collection of values, which is generically called iterable . The loop iterates over iterable while the conditional statement checks if the target value is equal to the current value. Note that the condition checks for object identity with is or for value equality with the equality operator ( == ). These are slightly different but complementary tests.
If the condition is true, then the function returns True , breaking out of the loop. This early return short-circuits the loop operation. If the loop finishes without any match, then the function returns False :
The first call to is_member() returns True because the target value, 5 , is a member of the list at hand, [2, 3, 5, 9, 7] . The second call to the function returns False because 8 isn’t present in the input list of values.
Membership tests like the ones above are so common and useful in programming that Python has dedicated operators to perform these types of checks. You can get to know the membership operators in the following table:
Operator | Description | Syntax |
---|---|---|
in | Returns True if the target value is present in a collection of values. Otherwise, it returns False . | value in collection |
not in | Returns True if the target value is not present in a given collection of values. Otherwise, it returns False . | value not in collection |
As with Boolean operators, Python favors readability by using common English words instead of potentially confusing symbols as operators.
Note: Don’t confuse the in keyword when it works as the membership operator with the in keyword in the for loop syntax. They have entirely different meanings. The in operator checks if a value is in a collection of values, while the in keyword in a for loop indicates the iterable that you want to draw from.
Like many other operators, in and not in are binary operators. That means you can create expressions by connecting two operands. In this case, those are:
- Left operand: The target value that you want to look for in a collection of values
- Right operand: The collection of values where the target value may be found
The syntax of a membership test looks something like this:
In these expressions, value can be any Python object. Meanwhile, collection can be any data type that can hold collections of values, including lists, tuples, strings, sets, and dictionaries. It can also be a class that implements the .__contains__() method or a user-defined class that explicitly supports membership tests or iteration.
If you use the in and not in operators correctly, then the expressions that you build with them will always evaluate to a Boolean value. In other words, those expressions will always return either True or False . On the other hand, if you try and find a value in something that doesn’t support membership tests, then you’ll get a TypeError . Later, you’ll learn more about the Python data types that support membership tests.
Because membership operators always evaluate to a Boolean value, Python considers them Boolean operators just like the and , or , and not operators.
Now that you know what membership operators are, it’s time to learn the basics of how they work.
Python’s in Operator
To better understand the in operator, you’ll start by writing some small demonstrative examples that determine if a given value is in a list:
The first expression returns True because 5 appears inside your list of numbers. The second expression returns False because 8 isn’t present in the list.
According to the in operator documentation, an expression like value in collection is equivalent to the following code:
The generator expression wrapped in the call to any() builds a list of the Boolean values that result from checking if the target value has the same identity or is equal to the current item in collection . The call to any() checks if any one of the resulting Boolean values is True , in which case the function returns True . If all the values are False , then any() returns False .
Python’s not in Operator
The not in membership operator does exactly the opposite. With this operator, you can check if a given value is not in a collection of values:
In the first example, you get False because 5 is in [2, 3, 5, 9, 7] . In the second example, you get True because 8 isn’t in the list of values. This negative logic may seem like a tongue twister. To avoid confusion, remember that you’re trying to determine if the value is not part of a given collection of values.
Note: The not value in collection construct works the same as the value not in collection one. However, the former construct is more difficult to read. Therefore, you should use not in as a single operator instead of using not to negate the result of in .
With this quick overview of how membership operators work, you’re ready to go to the next level and learn how in and not in work with different built-in data types.
Using in and not in With Different Python Types
All built-in sequences—such as lists, tuples, range objects, and strings—support membership tests with the in and not in operators. Collections like sets and dictionaries also support these tests. By default, membership operations on dictionaries check whether the dictionary has a given key or not. However, dictionaries also have explicit methods that allow you to use the membership operators with keys, values, and key-value pairs.
In the following sections, you’ll learn about a few particularities of using in and not in with different built-in data types. You’ll start with lists, tuples, and range objects to kick things off.
Lists, Tuples, and Ranges
So far, you’ve coded a few examples of using the in and not in operators to determine if a given value is present in an existing list of values. For these examples, you’ve explicitly used list objects. So, you’re already familiar with how membership tests work with lists.
With tuples, the membership operators work the same as they would with lists:
There are no surprises here. Both examples work the same as the list-focused examples. In the first example, the in operator returns True because the target value, 5 , is in the tuple. In the second example, not in returns the opposite result.
For lists and tuples, the membership operators use a search algorithm that iterates over the items in the underlying collection. Therefore, as your iterable gets longer, the search time increases in direct proportion. Using Big O notation, you’d say that membership operations on these data types have a time complexity of O(n).
If you use the in and not in operators with range objects, then you get a similar result:
When it comes to range objects, using membership tests may seem unnecessary at first glance. Most of the time, you’ll know the values in the resulting range beforehand. But what if you’re using range() with offsets that are determined at runtime?
Note: When creating range objects, you can pass up to three arguments to range() . These arguments are start , stop , and step . They define the number that starts the range, the number at which the range must stop generating values, and the step between the generated values. These three arguments are commonly known as offsets.
Consider the following examples, which use random numbers to determine offsets at runtime:
On your machine, you might get different results because you’re working with random range offsets. In these specific examples, step is the only offset that varies. In real code, you could have varying values for the start and stop offsets as well.
For range objects, the algorithm behind the membership tests computes the presence of a given value using the expression (value — start) % step) == 0 , which depends on the offsets used to create the range at hand. This makes membership tests very efficient when they operate on range objects. In this case, you’d say that their time complexity is O(1).
Note: Lists, tuples, and range objects have an .index() method that returns the index of the first occurrence of a given value in the underlying sequence. This method is useful for locating a value in a sequence.
Some may think that they can use the method to determine if a value is in a sequence. However, if the value isn’t in the sequence, then .index() raises a ValueError :
You probably don’t want to figure out whether a value is in a sequence or not by raising exceptions, so you should use a membership operator instead of .index() for this purpose.
Remember that the target value in a membership test can be of any type. The test will check if that value is or isn’t in the target collection. For example, say that you have a hypothetical app where the users authenticate with a username and a password. You can have something like this:
This is a naive example. It’s unlikely that anyone would handle their users and passwords like this. But the example shows that the target value can be of any data type. In this case, you use a tuple of strings representing the username and the password of a given user.
Here’s how the code works in practice:
In the first example, the username and password are correct because they’re in the users list. In the second example, the username doesn’t belong to any registered user, so the authentication fails.
In these examples, it’s important to note that the order in which the data is stored in the login tuple is critical because something like («john», «secret») isn’t equal to («secret», «john») in tuple comparison even if they have the same items.
In this section, you’ve explored examples that showcase the core behavior of membership operators with common Python built-in sequences. However, there’s a built-in sequence left. Yes, strings! In the next section, you’ll learn how membership operators work with this data type in Python.
Strings
Python strings are a fundamental tool in every Python developer’s tool kit. Like tuples, lists, and ranges, strings are also sequences because their items or characters are sequentially stored in memory.
You can use the in and not in operators with strings when you need to figure out if a given character is present in the target string. For example, say that you’re using strings to set and manage user permissions for a given resource:
The User class takes two arguments, a username and a set of permissions. To provide the permissions, you use a string in which w means that the user has write permission, r means that the user has read permission, and x implies execution permissions. Note that these letters are the same ones that you’d find in the Unix-style file-system permissions.
The membership test inside has_permission() checks whether the current user has a given permission or not, returning True or False accordingly. To do this, the in operator searches the permissions string to find a single character. In this example, you want to know if the users have write permission.
However, your permission system has a hidden issue. What would happen if you called the function with an empty string? Here’s your answer:
Because an empty string is always considered a substring of any other string, an expression like «» in user.permissions will return True . Depending on who has access to your users’ permissions, this behavior of membership tests may imply a security breach in your system.
You can also use the membership operators to determine if a string contains a substring:
For the string data type, an expression like substring in string is True if substring is part of string . Otherwise, the expression is False .
Note: Unlike other sequences like lists, tuples, and range objects, strings provide a .find() method that you can use when searching for a given substring in an existing string.
For example, you can do something like this:
If the substring is present in the underlying string, then .find() returns the index at which the substring starts in the string. If the target string doesn’t contain the substring, then you get -1 as a result. So, an expression like string.find(substring) >= 0 would be equivalent to a substring in string test.
However, the membership test is way more readable and explicit, which makes it preferable in this situation.
An important point to remember when using membership tests on strings is that string comparisons are case-sensitive:
This membership test returns False because strings comparisons are case-sensitive, and «PYTHON» in uppercase isn’t present in greeting . To work around this case sensitivity, you can normalize all your strings using either the .upper() or .lower() method:
In this example, you use .lower() to convert the target substring and the original string into lowercase letters. This conversion tricks the case sensitivity in the implicit string comparison.
Generators
Generator functions and generator expressions create memory-efficient iterators known as generator iterators. To be memory efficient, these iterators yield items on demand without keeping a complete series of values in memory.
In practice, a generator function is a function that uses the yield statement in its body. For example, say that you need a generator function that takes a list of numbers and returns an iterator that yields square values from the original data. In this case, you can do something like this:
This function returns a generator iterator that yields square numbers on demand. You can use the built-in next() function to retrieve consecutive values from the iterator. When the generator iterator is completely consumed, it raises a StopIteration exception to communicate that no more values are left.
You can use the membership operators on a generator function like squares_of() :
The in operator works as expected when you use it with generator iterators, returning True if the value is present in the iterator and False otherwise.
However, there’s something you need to be aware of when checking for membership on generators. A generator iterator will yield each item only once. If you consume all the items, then the iterator will be exhausted, and you won’t be able to iterate over it again. If you consume only some items from a generator iterator, then you can iterate over the remaining items only.
When you use in or not in on a generator iterator, the operator will consume it while searching for the target value. If the value is present, then the operator will consume all the values up to the target value. The rest of the values will still be available in the generator iterator:
In this example, 4 is in the generator iterator because it’s the square of 2 . Therefore, in returns True . When you use next() to retrieve a value from square , you get 9 , which is the square of 3 . This result confirms that you no longer have access to the first two values. You can continue calling next() until you get a StopIteration exception when the generator iterator is exhausted.
Likewise, if the value isn’t present in the generator iterator, then the operator will consume the iterator completely, and you won’t have access to any of its values:
In this example, the in operator consumes squares completely, returning False because the target value isn’t in the input data. Because the generator iterator is now exhausted, a call to next() with squares as an argument raises StopIteration .
You can also create generator iterators using generator expressions. These expressions use the same syntax as list comprehensions but replace the square brackets ( [] ) with round brackets ( () ). You can use the in and not in operators with the result of a generator expression:
The squares variable now holds the iterator that results from the generator expression. This iterator yields square values from the input list of numbers. Generator iterators from generator expressions work the same as generator iterators from generator functions. So, the same rules apply when you use them in membership tests.
Another critical issue can arise when you use the in and not in operators with generator iterators. This issue can appear when you’re working with infinite iterators. The function below returns an iterator that yields infinite integers:
The infinite_integers() function returns a generator iterator, which is stored in integers . This iterator yields values on demand, but remember, there will be infinite values. Because of this, it won’t be a good idea to use the membership operators with this iterator. Why? Well, if the target value isn’t in the generator iterator, then you’ll run into an infinite loop that’ll make your execution hang.
Dictionaries and Sets
Python’s membership operators also work with dictionaries and sets. If you use the in or not in operators directly on a dictionary, then it’ll check whether the dictionary has a given key or not. You can also do this check using the .keys() method, which is more explicit about your intentions.
You can also check if a given value or key-value pair is in a dictionary. To do these checks, you can use the .values() and .items() methods, respectively:
In these examples, you use the in operator directly on your likes dictionary to check whether the «fruit» , «hobby» , and «blue» keys are in the dictionary or not. Note that even though «blue» is a value in likes , the test returns False because it only considers the keys.
Next up, you use the .keys() method to get the same results. In this case, the explicit method name makes your intentions much clearer to other programmers reading your code.
To check if a value like «dog» or «drawing» is present in likes , you use the .values() method, which returns a view object with the values in the underlying dictionary. Similarly, to check if a key-value pair is contained in likes , you use .items() . Note that the target key-value pairs must be two-item tuples with the key and value in that order.
If you’re using sets, then the membership operators work as they would with lists or tuples:
These examples show that you can also check whether a given value is contained in a set by using the membership operators in and not in .
Now that you know how the in and not in operators work with different built-in data types, it’s time to put these operators into action with a couple of examples.
Putting Python’s in and not in Operators Into Action
Membership tests with in and not in are pretty common operations in programming. You’ll find these kinds of tests in many existing Python codebases, and you’ll use them in your code as well.
In the following sections, you’ll learn how to replace Boolean expressions based on the or operator with membership tests. Because membership tests can be quite common in your code, you’ll also learn how to make these tests more efficient.
Replacing Chained or Operators
Using a membership test to replace a compound Boolean expression with several or operators is a useful technique that allows you to simplify your code and make it more readable.
To see this technique in action, say that you need to write a function that takes a color name as a string and determines whether it’s a primary color. To figure this out, you’ll use the RGB (red, green, and blue) color model:
In is_primary_color() , you use a compound Boolean expression that uses the or operator to check if the input color is either red, green, or blue. Even though this function works as expected, the condition may be confusing and difficult to read and understand.
The good news is that you can replace the above condition with a compact and readable membership test:
Now your function uses the in operator to check whether the input color is red, green, or blue. Assigning the set of primary colors to a properly named variable like primary_colors also helps to make your code more readable. The final check is pretty clear now. Anyone reading your code will immediately understand that you’re trying to determine if the input color is a primary color according to the RGB color model.
If you look at the example again, then you’ll notice that the primary colors have been stored in a set. Why? You’ll find your answer in the following section.
Writing Efficient Membership Tests
Python uses a data structure called a hash table to implement dictionaries and sets. Hash tables have a remarkable property: looking for any given value in the data structure takes about the same time, no matter how many values the table has. Using Big O notation, you’ll say that value lookups in hash tables have a time complexity of O(1), which makes them super fast.
Now, what does this feature of hash tables have to do with membership tests on dictionaries and sets? Well, it turns out that the in and not in operators work very quickly when they operate on these types. This detail allows you to optimize your code’s performance by favoring dictionaries and sets over lists and other sequences in membership tests.
To have an idea of how much more efficient than a list a set can be, go ahead and create the following script:
This script creates a list of integer numbers with one hundred thousand values and a set with the same number of elements. Then the script computes the time that it takes to determine if the number -1 is in the list and the set. You know up front that -1 doesn’t appear in the list or set. So, the membership operator will have to check all the values before getting a final result.
As you already know, when the in operator searches for a value in a list, it uses an algorithm with a time complexity of O(n). On the other hand, when the in operator searches for a value in a set, it uses the hash table lookup algorithm, which has a time complexity of O(1). This fact can make a big difference in terms of performance.
Go ahead and run your script from the command line using the following command:
Although your command’s output may be slightly different, it’ll still show a significant performance difference when you use a set instead of a list in this specific membership test. With a list, the processing time will be proportional to the number of values. With a set, the time will be pretty much the same for any number of values.
This performance test shows that when your code is doing membership checks on large collections of values, you should use sets instead of lists whenever possible. You’ll also benefit from sets when your code performs several membership tests during its execution.
However, note that it’s not a good idea to convert an existing list into a set just to perform a few membership tests. Remember that converting a list into a set is an operation with O(n) time complexity.
Using operator.contains() for Membership Tests
The in operator has an equivalent function in the operator module, which comes in the standard library. The function is called contains() . It takes two arguments—a collection of values and a target value. It returns True if the input collection contains the target value:
The first argument to contains() is the collection of values, and the second argument is the target value. Note that the order of arguments differs from a regular membership operation, where the target value comes first.
This function comes in handy when you’re using tools like map() , or filter() to process iterables in your code. For example, say you have a bunch of Cartesian points stored as tuples inside a list. You want to create a new list containing only the points that aren’t over the coordinate axis. Using the filter() function, you can come up with the following solution:
In this example, you use filter() to retrieve the points that don’t contain a 0 coordinate. To do this, you use contains() in a lambda function. Because filter() returns an iterator, you wrap up everything in a call to list() to convert the iterator into a list of points.
Even though the construct in the above example works, it’s quite complex because it implies importing contains() , creating a lambda function on top of it, and calling a couple of functions. You can get the same result using a list comprehension either with contains() or the not in operator directly:
The above list comprehensions are shorter and arguably more readable than the equivalent filter() call from the previous example. They’re also less complex because you don’t need to create a lambda function or call list() , so you’re reducing the knowledge requirements.
Supporting Membership Tests in User-Defined Classes
Providing a .__contains__() method is the most explicit and preferred way to support membership tests in your own classes. Python will automatically call this special method when you use an instance of your class as the right operand in a membership test.
You’ll likely add a .__contains__() method only to classes that’ll work as collections of values. That way, the users of your class will be able to determine if a given value is stored in a specific instance of your class.
As an example, say that you need to create a minimal stack data structure to store values following the LIFO (last in, first out) principle. One requirement of your custom data structure is to support membership tests. So, you end up writing the following class:
Your Stack class supports the two core functionalities of stack data structures. You can push a value to the top of the stack and pop a value from the top of the stack. Note that your data structure uses a list object under the hood to store and manipulate the actual data.
Your class also supports membership tests with the in and not in operators. To do this, the class implements a .__contains__() method that relies on the in operator itself.
To try out your class, go ahead and run the following code:
Your class fully supports the in and not in operators. Great job! You now know how to support membership tests in your own classes.
Note that if a given class has a .__contains__() method, then the class doesn’t have to be iterable for the membership operators to work. In the example above, Stack isn’t iterable, and the operators still work because they retrieve their result from the .__contains__() method.
There are at least two more ways to support membership tests in user-defined classes apart from providing a .__contains__() method. If your class has either an .__iter__() or a .__getitem__() method, then the in and not in operators also work.
Consider the following alternative version of Stack :
The .__iter__() special method makes your class iterable, which is enough for membership tests to work. Go ahead and give it a try!
Another way to support membership tests is to implement a .__getitem__() method that handles indexing operations using zero-based integer indices in your classes:
Python automatically calls the .__getitem__() method when you perform indexing operations on the underlying object. In this example, when you do stack[0] , you’ll get the first item in the Stack instance. Python takes advantage of .__getitem__() to make the membership operators work correctly.
Conclusion
Now you know how to perform membership tests using Python’s in and not in operators. This type of test allows you to check if a given value is present in a collection of values, which is a pretty common operation in programming.
In this tutorial, you’ve learned how to:
- Run membership tests using Python’s in and not in operators
- Use the in and not in operators with different data types
- Work with operator.contains() , the equivalent function to the in operator
- Support in and not in in your own classes
With this knowledge, you’re good to go with membership tests using Python’s in and not in operators in your code.
Source Code: Click here to download the free source code that you’ll use to perform membership tests in Python with in and not in .
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.
Similarly, you can check if a value is not in a collection with not in operation (combining the not operator and the in operator):
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:
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:
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:
- A character exists in a string.
- A substring exists in a string.
For example, let’s see if “Hello” exists in “Hello world”:
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:
If a key-value pair does not exist in the dictionary and you try to access it this way, you would see an error.
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:
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.