To check if elements are part of a list in Python, you can use the in
operator. Here’s an example:
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
print("3 is in the list")
else:
print("3 is not in the list")
if 6 in my_list:
print("6 is in the list")
else:
print("6 is not in the list")
In this example, we have a list called my_list
containing integers. We use the in
operator to check if certain elements are present in the list.
In the first if
statement, we check if 3
is in my_list
. Since 3
is present in the list, the condition 3 in my_list
evaluates to True
, and we print “3 is in the list”.
In the second if
statement, we check if 6
is in my_list
. Since 6
is not present in the list, the condition 6 in my_list
evaluates to False
, and we print “6 is not in the list”.
The in
operator returns True
if the element is found in the list and False
otherwise. You can use this operator to check the presence of multiple elements as well by chaining multiple in
operations or using it in a loop to iterate over a collection of elements.
+ There are no comments
Add yours