Open In App

Check if element exists in list in Python

Last Updated : 29 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

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:

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.

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

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.

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

  • in Statement: The simplest and most efficient method for checking if an element exists in a list. Ideal for most cases.
  • for Loop: Allows manual iteration and checking and provides more control but is less efficient than using ‘in’.
  • any(): A concise option that works well when checking multiple conditions or performing comparisons directly on list.
  • count(): Useful for finding how many times an element appears in the list but less efficient for checking existance of element only.

Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg