Python: Find in list

To check if an item exists in a list in Python, you can use the in operator. Here’s an example:

css

list = [1, 2, 3, 4, 5]
if 3 in list:
print("3 exists in the list")

This would produce the following output:

perl

3 exists in the list

You can also use the index method to find the first index of an item in a list. If the item is not found in the list, an exception ValueError will be raised. Here’s an example:

python

list = [1, 2, 3, 4, 5]
try:
index = list.index(3)
print("The index of 3 is", index)
except ValueError:
print("3 is not in the list")

This would produce the following output:

python

The index of 3 is 2