How can I find a value in a list using Python?

I currently use the following code to check if an item is in my_list:

if item in my_list:
    print("Desired item is in the list")

Is using if item in my_list: the most “pythonic” way to find an item in a list?

As for your first question: if item in my_list: is perfectly fine and should work if item exactly matches one of the elements in my_list. Note that the comparison is case-sensitive, so “abc” and “ABC” are considered different. Floating point values may also have precision issues, such as 1 - 1/3 != 2/3.

Regarding your second question: There are several ways to “find” things in lists.

Checking if an item is in the list: This is the use case you described. You can use the in operator:

3 in [1, 2, 3]  # => True

Filtering a collection: To find all elements in a list that meet a certain condition, you can use list comprehensions or generator expressions:

matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

The second line returns a generator, a lazy list that is built as you iterate through it. The first line is equivalent to:

matches = filter(fulfills_some_condition, lst)

In Python 2, filter returns a list, while in Python 3, it returns a generator-like object.

Finding the first occurrence: To find the first element that matches a condition, you can use a for loop, possibly with the else clause. Alternatively, use:

next(x for x in lst if ...)

This returns the first match or raises a StopIteration if none is found. You can also provide a default value:

next((x for x in lst if ...), [default value])

Finding the location of an item: To find the index of an element in a list, use the index method:

[1, 2, 3].index(2)  # => 1
[1, 2, 3].index(4)  # => ValueError

Note that index returns the first occurrence:

[1, 2, 3, 2].index(2)  # => 1

For finding all occurrences, use enumerate:

[i for i, x in enumerate([1, 2, 3, 2]) if x == 2]  # => [1, 3]

To find the first occurrence of a value in an iterable, you can use a recipe from the itertools module called first_true. This function returns the first true value in the iterable. If no true value is found, it returns a default value.

Here’s the first_true function:

def first_true(iterable, default=False, pred=None):
    """
    Returns the first true value in the iterable.

    If no true value is found, returns *default*.

    If *pred* is not None, returns the first item
    for which pred(item) is true.
    """
    return next(filter(pred, iterable), default)

You can use it like this:

first_true([2, 3, 4, 5], None, lambda x: x % 2 == 1)

This will return 3, which is the first odd number in the list.

You can copy and paste this function, or if you prefer, you can install the more-itertools package, which includes this recipe:

pip install more-itertools

This way, you can use the first_true function without defining it yourself.

The count() method returns the number of elements in a list that have the specified value.

Syntax

list.count(value)

Example

fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")

Question’s Example

item = someSortOfSelection()

if myList.count(item) >= 1:
    doMySpecialFunction(item)

In this example, myList.count(item) is used to check if item appears at least once in myList, and if it does, doMySpecialFunction(item) is called.