search

What is the use of the "in" keyword in Python?

The in keyword in Python is used as an operator to test if a value is present in a sequence or collection. It returns a boolean value, True or False, depending on whether the value is found or not. The in keyword is primarily used in conjunction with sequences like strings, lists, tuples, and sets.

Here's an example to illustrate the usage of the in keyword:

fruits = ['apple', 'banana', 'orange']

# Using the 'in' keyword
if 'banana' in fruits:
    print("Found banana in the list!")
else:
    print("Banana is not in the list.")

Output:

Found banana in the list!

In the above example, the in keyword checks if the value 'banana' is present in the fruits list. Since 'banana' exists in the list, the condition is evaluated as True, and the corresponding message is printed.

The in keyword can also be used with other sequence types, such as strings and tuples:

string = "Hello, World!"

# Using the 'in' keyword with a string
if 'o' in string:
    print("The letter 'o' is in the string.")
else:
    print("The letter 'o' is not in the string.")

Output:

The letter 'o' is in the string.

Similarly, you can use the in keyword to check for membership in sets or to search for keys in dictionaries:

my_set = {1, 2, 3}

# Using the 'in' keyword with a set
if 4 in my_set:
    print("Found 4 in the set!")
else:
    print("4 is not in the set.")

Output:

4 is not in the set.

The in keyword provides a simple and concise way to check for the presence of a value in a sequence or collection. It is widely used in conditionals, loops, and other programming constructs to determine if a value is part of a particular data structure.

Related Questions You Might Be Interested