Home » Programming » Python » Python Find In List

Python Find in List: Check if an Element is Present

Python offers several different types of arrays for storing data.

Lists are arrays which allow you to store items. These list items can be altered, and are stored in a specific order.

There are several methods you should consider for searching a list in Python– searching for a specific value match, or searching for list items that match a certain condition or set of conditions.

You can also remove items from a list in Python.

Checking if a List Contains an Item Using the ‘in’ Statement

Syntax

The syntax for the ‘in’ statement is as follows:

element in list

It will return TRUE or FALSE as a boolean value depending on the outcome.

Example

Here it is in action:

sports = ["cricket", "tennis", "baseball"]
if "tennis" in sports:
    print "tennis is present in the list"

Checking if List Does NOT Contain an Item Using not in

You can also check that a list does not contain a value:

sports = ["cricket", "tennis", "baseball"]
if "basketball" not in sports:
    print "basketball is not present in the list"

Checking Using the count() Function

Syntax

The count() function can also be used to check whether an item is present in a list – and it will also tell you how many times it appears:

list.count(element)

It will return an integer count of the number of times the element was encountered.

Example

sports = ["cricket", "tennis", "baseball", "tennis"]
count = sports.count("tennis")
print count # Returns 2

You can then check that the value of count is greater than 0 to see whether the element is present or take another action if the count is higher.

Checking for Items which have a Value Matching Custom Conditions Using any()

Syntax

any(condition for element in list)

It will return TRUE or FALSE as a boolean value depending on the outcome.

Example

sports = ["cricket", "tennis", "baseball"]
result = any(len(sport) == 7 for sport in sports)
print result # Returns TRUE

The above example checks whether there is an element in the list with 7 letters in it. “cricket” is a match for this, so TRUE is returned.

Conclusion

Common uses for checking whether an item is present in a list may include checking whether a user in your app is a member of a group, whether a certain color of product you have for sale is available, or checking whether a correct answer has been entered for a quiz.

Check out our other Python articles here!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment