Home »
Python
Python in Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
The in is a keyword (case-sensitive) in python, it is used to check whether an element exists in the given sequence like string, list, tuple, etc.
The in keyword is also used with the for loop to iterate the sequence.
Syntax
Syntax of in keyword:
if element in sequence:
statement(s)
for element in sequence:
statement(s)
Sample Input/Output
Input:
cities = ["New Delhi", "Mumbai", "Chennai", "Banglore"]
# condition
if "Mumbai" in cities:
print("Yes")
else:
print("No")
Output:
Yes
Example 1
Check whether an element exits in a list of not.
# python code to demonstrate example of
# in keyword
# Check whether an element exits in a list of not
# create a list
cities = ["New Delhi", "Mumbai", "Chennai", "Banglore"]
# check if "Mumbai" is present in the list or not
if "Mumbai" in cities:
print("Yes \"Mumbai\" exists in the list")
else:
print("No \"Mumbai\" does not exist in the list")
# now check...
# "Gwalior" is present in the list or not
if "Gwalior" in cities:
print("Yes \"Gwalior\" exists in the list")
else:
print("No \"Gwalior\" does not exist in the list")
Output
Yes "Mumbai" exists in the list
No "Gwalior" does not exist in the list
Example 2
Take a string and print the characters one by one until a dot (".") is not found.
# python code to demonstrate example of
# in keyword
# Take a string and print the characters one by one
# until a dot ('.') is not found.
# string input
string = input("Enter a string: ")
# print characters until dot is not found
for ch in string:
if ch=='.':
break
print(ch)
Output
Enter a string: IncludeHelp.com
I
n
c
l
u
d
e
H
e
l
p