Use in Operator
In the previous step, you learned the basics of list membership using the in
operator. In this step, we will explore more practical applications of the in
operator with different data types and scenarios.
The in
operator is not limited to just lists. It can also be used with other iterable data types like strings and tuples.
Using in
with Strings:
You can check if a substring exists within a larger string. Create a file named string_membership.py
in your ~/project
directory using the VS Code editor. Add the following code to string_membership.py
:
text = "Hello, world!"
print("world" in text)
Save the file. Now, execute the script using the following command in the terminal:
python string_membership.py
The output will be:
True
This indicates that the substring "world" is present in the string "Hello, world!".
Let's try checking for a substring that doesn't exist:
text = "Hello, world!"
print("python" in text)
Save the file and execute it again:
python string_membership.py
The output will be:
False
This indicates that the substring "python" is not present in the string "Hello, world!".
Using in
with Tuples:
Tuples are similar to lists but are immutable (cannot be changed after creation). You can also use the in
operator with tuples. Create a file named tuple_membership.py
in your ~/project
directory using the VS Code editor. Add the following code to tuple_membership.py
:
numbers = (1, 2, 3, 4, 5)
print(3 in numbers)
Save the file. Now, execute the script using the following command in the terminal:
python tuple_membership.py
The output will be:
True
This indicates that the number 3 is present in the tuple numbers
.
Let's check for a number that doesn't exist:
numbers = (1, 2, 3, 4, 5)
print(6 in numbers)
Save the file and execute it again:
python tuple_membership.py
The output will be:
False
This indicates that the number 6 is not present in the tuple numbers
.
These examples demonstrate the versatility of the in
operator in Python. It can be used to check for membership in various iterable data types, making it a valuable tool for writing concise and readable code.