![]() |
VOOZH | about |
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:
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.
The in keyword in Python serves two primary purposes:
for loop.The in keyword can be used with both if statements and forloops.
Using in with if statement:
if element in sequence:
# Execute statement
Using in with for loop:
for element in sequence:
# Execute statement
Let’s explore how the in keyword functions with different Python data structures .
In this example, we will check if the string "php" is present in a list of programming languages. If it is, the program will print True.
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.
Here, we will use the in keyword to loop through each character of the string "GeeksforGeeks" and print each character until the character 'f' is encountered, at which point the loop will stop.
G e e k s
Explanation: The for 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.
In this case, we will check if the key "Alice" exists in a dictionary of student names and marks. If the key is found, we will print Alice's marks.
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.
We will check if the character 'e' is present in a set of vowels and print the result as True or False based on its presence.
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.