Check if element exists in list in Python (original) (raw)

Last Updated : 29 Nov, 2024

In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the **in Keyword.

**Example:

Python `

a = [10, 20, 30, 40, 50]

Check if 30 exists in the list

if 30 in a: print("Element exists in the list") else: print("Element does not exist")

`

Output

Element exists in the list

**Let’s explore other different methods to check if element exists in list:

Table of Content

Using a loop

Using **for loop we can iterate over each element in the list and check if an element exists. Using this method, we have an extra control during checking elements.

Python `

a = [10, 20, 30, 40, 50]

Check if 30 exists in the list using a loop

key = 30 flag = False

for val in a: if val == key: flag = True break

if flag: print("Element exists in the list") else: print("Element does not exist")

`

Output

Element exists in the list

**Note: This method is less efficient than using ‘in’.

Using any()

The any() function is used to check if any element in an iterable evaluates to **True. It returns **True if at least one element in the iterable is truthy (i.e., evaluates to **True), otherwise it returns **False

Python `

a = [10, 20, 30, 40, 50]

Check if 30 exists using any() function

flag = any(x == 30 for x in a)

if flag: print("Element exists in the list") else: print("Element does not exist")

`

Output

Element exists in the list

Using count()

The count() function can also be used to check if an element exists by counting the occurrences of the element in the list. It is useful if we need to know the number of times an element appears.

Python `

a = [10, 20, 30, 40, 50]

Check if 30 exists in the list using count()

if a.count(30) > 0: print("Element exists in the list") else: print("Element does not exist")

`

Output

Element exists in the list

Which Method to Choose

Similar Reads

Basic Programs







Array Programs








List Programs







Matrix Programs









String Programs







Dictionary Programs







Tuple Programs







Searching and Sorting Programs







Pattern Printing Programs