Python Fastest Way to Check if Item in List

Python’s List is the container for different data types like integer, string, dictionary, boolean, and tuple. Let’s take the simple example of a list that holds all those data types.

mixed_lst = ['check', 7, True, {"lang": "Python"}, (4, 5, 6)]

We can print those list items individually using for loop as:

for item in mixed_lst:
    print(item)

Output:

check
7
True
{'lang': 'Python'}
(4, 5, 6)

 

Checking methods in the List

We know how Python list actually works. There is a time come when you want to search for specific items in the list. To search the item we will discuss three main methods here in this blog.

Problem Scenario:
We create a list of 1000 items which contains multiples of 7. Then we will check whether the item exists in the list or not. Those items that exist will be the multiples of 7 and those that don’t exist will not be the multiples of 7.

Let’s create 1000 multiples of 7 in the list as:

multiples_7_lst = [item * 7 for item in range(1000)]

Output:

[0,
7,
14,
21,
28,
35,
42,
......
......

 

Method 1: Naive method using == operator

This method uses for loop in order to check whether the item exists or not. Those items that exist return value as “It is multiple of 7”.

Check whether 581 exists in that list or not

check_item = 581

for item in multiples_7_lst:
    if item == check_item:
        print('It is multiple of 7')

Output:

It is multiple of 7

 

Method 2: Using Python “in” keyword

This method “in” keyword is pretty used by almost all the advanced Python developers to check the presence of items in the list and it is more straightforward and easy to implement. It is also the most recommended approach.

It returns a boolean value as True if that item exists in the list by default.

>>> multiples_7_lst = [item * 7 for item in range(1000)]
>>> 500 in multiples_7_lst
False
>>> 581 in multiples_7_lst
True
>>>

 

Let’s format the output using the if else statement as:

check_item = 343

if check_item in multiples_7_lst:
    print(f'{check_item} is a multiple of 7')
else:
    print(f'{check_item} is not a multiple of 7')

Output:

343 is a multiple of 7

 

Method 3: Using count method of the list

This method usually tells how many times the particular item repeats in the list. Say if the item repeats n times, then the count method returns values as n times.

If no item is present in the list, then it returns a value of 0.

>>> multiples_7_lst = [item * 7 for item in range(1000)]
>>> multiples_7_lst.count(1001)
1
>>> multiples_7_lst.count(7077)
0

 

Let’s format this output too using the if else statement as:

check_item = 917

if multiples_7_lst.count(check_item) > 0:
    print(f'{check_item} is a multiple of 7')
else:
    print(f'{check_item} is not a multiple of 7')

Output:

917 is a multiple of 7

Leave a Comment