Open In App
Related Articles

Python in Keyword

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In programming, a keyword is a “reserved word” by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Python, keywords are case-sensitive.

Python in Keyword

The ‘in’ keyword in Python returns True if a certain element is present in a Python object, else it will return False. It has two purposes:

  • To check if a value is present in a list, tuple, range, string, etc.
  • To iterate through a sequence in a for loop.

Python ‘in’ keyword in Expression

The in keyword in Python can be used with if statements as well as with for loops. It has the following syntax:

# Using if statement
if element in sequence:
    # statement

# Using for statement
for element in sequence:
    # statement

Python in Keyword Usage

Let us see a few examples to know how the “in” keyword works in Python.

“in” Keyword with Python if Statement

In this example, we will create a Python list of animals. Then we will use the in keyword with the if statement to check the presence of “lion” in animals.

Python3

# Python program to demonstrate
# in keyword
  
# Create a list
animals = ["dog", "lion", "cat"]
  
# Check if lion in list or not
if "lion" in animals:
    print("Yes")

                    

Output:

Yes

Use of in keyword in for loop in Python

In this example, we will first define a Python String, and use for loop to iterate over each character in that string.

Python3

# Python program to demonstrate
# in keyword
  
# Create a string
s = "GeeksforGeeks"
  
# Iterating through the string
for i in s:
      
    # if f occurs in the string
    # break the loop
    if i == 'f':
        break
      
    print(i)

                    

Output:

G
e
e
k
s



Last Updated : 08 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads