Which membership operator is used to check if an item exists in a list in Python?
a) in
b) not in
c) exists
d) contains
Answer:
a) in
Explanation:
The in operator in Python is used to check if an item exists in a list, tuple, string, or any other iterable. It returns True if the item is found and False otherwise.
fruits = ["apple", "banana", "cherry"]
result = "banana" in fruits # result is True
Membership operators like in and not in are incredibly useful in various scenarios, such as validating user input, searching for specific items in a collection, or filtering data.
Using the in operator is more efficient and readable than manually iterating through a list to check for an item’s existence, making it a preferred approach in Pythonic code.