This tutorial shows examples of checking if an item is in a Python list.
Method 1:
item in list_name
Method 2:
list_name.index(item)
Method 3:
list_name.count(item)
Example for method 1: Check if an item in a list
The following code checks if the item of number 6 is in a list.
# creat a list
list_1=[7, 6, 5, 4]
# check if the item of 6 is in the list
6 in list_1
The following is the output, which shows True
.
True
Example for method 2: locate an item
The following Python code checks the location of an item in a list.
# check if item 7 is in the list
[7, 6, 5, 4].index(7)
# check if item 8 is in the list
[7, 6, 5, 4].index(8)
The output are 0
(which is the location of 7) and ValueError
.
0 ValueError: 8 is not in list
Example for method 3: count the number
The following code counts the number of an item in a list.
# Create a list
list_2=[7, 6, 5, 4, 6]
# count the number of the item in the list
list_2.count(6)
The following is the output. It indicates that the number is 2 since there are 2 6 in the list.
2