Python in Keyword
The in
keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set, or dictionary.
Example:
s = "Geeks for geeks"
if "for" in s:
print("found")
else:
print("not found")
Output
found
Explanation: if “for” in s checks if the substring “for” exists in the string s using the in keyword, which performs a membership test.
Purpose of the in keyword
The in
keyword in Python serves two primary purposes:
- Membership Testing: To check if a value exists in a sequence such as a list, tuple, set, range, dictionary, or string.
- Iteration: To iterate through elements of a sequence in a
for
loop.
Syntax of Python in Keyword
The in
keyword can be used with both if
statements and for
loops.
Using in with if statement:
if element in sequence:
# Execute statement
Using in with for loop:
for element in sequence:
# Execute statement
Usage of in keyword
Let’s explore how the in
keyword functions with different Python data structures .
Example 1: in
Keyword with if
Statement
a = ["php", "python", "java"]
# Check if "lion" is present in the list
if "php" in a:
print(True)
Output
True
Explanation: The in
operator checks if the string “php” is present in the list a
. Since “php” exists in the list, the output will be True
.
Example 2: in keyword in a for loop
s = "GeeksforGeeks"
# iterating through the string
for char in s:
if char == 'f':
break # Stop iteration when 'f' is found
print(char)
Output
G e e k s
Explanation: Thefor
loop iterates through each character in the strings
. The loop prints each character until it encounters ‘f’, at which point it breaks the loop and stops execution.
Example 3: in keyword with dictionaries.
d = {"Alice": 90, "Bob": 85}
# check if "Alice" is a key in `d`
if "Alice" in d:
print("Alice's marks are:", d["Alice"])
Output
Alice's marks are: 90
Explanation: The in
operator checks whether “Alice” is present as a key in dictionary d
. Since “Alice” is a key, it prints her marks.
Example 4: in keyword with sets.
v = {'a', 'e', 'i', 'o', 'u'} # vowels
# Check if 'e' is in the set
print('e' in v)
Output
True
Explanation: The in
operator checks if ‘e’ is present in the set v
. Since ‘e’ exists in the set, the output will be True
.