The in keyword is a membership operator used to check whether an element exists in a sequence, such as a list, tuple, string, set, or dictionary. It returns True if the element is found; otherwise, it returns False.
text = "Python Programming"
if "Python" in text:
print("Found")
else:
print("Not found")
Output
Found
Explanation: condition "Python" in text checks whether the substring "Python" is present in the string text. Since it exists, the condition evaluates to True, and the print() statement is executed.
Syntax
The general syntax of the in keyword is shown below:
element in sequence
Or, it can be used inside an if statement as follows:
if element in sequence:
# code
Explanation: in keyword checks whether an element exists in a sequence. It returns True if the element is found; otherwise, it returns False.
In Conditional Statements
The in keyword is used with if statements to check whether an element exists in a sequence.
fruits = ["apple", "banana", "mango"]
if "banana" in fruits:
print("Banana is available")
Output
Banana is available
Explanation: in keyword checks whether "banana" exists in the list. Since it is present, the condition evaluates to True.
In for Loops
The in keyword is also used in for loops to iterate over the elements of a sequence.
colors = ["Red", "Green", "Blue"]
for color in colors:
print(color)
Output
Red Green Blue
Explanation: for loop uses the in keyword to access each element of the list one by one.
With Dictionaries
When used with dictionaries, the in keyword checks whether a key exists in the dictionary.
student = { "name": "Yoir", "marks": 90 }
if "marks" in student:
print(student["marks"])
Output
90
Explanation: in keyword checks whether "marks" is a key in the dictionary. Since the key exists, its corresponding value is printed.
With Strings
The in keyword can be used to check whether a character or substring exists in a string.
message = "Welcome to Python"
print("Python" in message)
print("Java" in message)
Output
True False
Explanation:
- "Python" is present in the string, so the result is True.
- "Java" is not present, so the result is False.
With Sets
The in keyword provides a simple way to check whether an element exists in a set.
vowels = {"a", "e", "i", "o", "u"}
if "e" in vowels:
print("e is a vowel")
Output
e is a vowel
Explanation: in keyword checks whether "e" is present in the set. Since it exists, the condition evaluates to True.