Finding an element within a list

Published

2023-08-01

Finding an element within a sequence

It should come as no surprise that if we have a sequence of objects, we often wish to see if an element is in the sequence (list, tuple, or string). Sometimes we also want to find the index of the element within a sequence. Python makes this relatively straightforward.

Checking to see if an element is in a sequence

Say we have the following list:

>>> fruits = ['kumquat', 'papaya', 'kiwi', 'lemon', 'lychee']

We can check to see if an element exists using the Python keyword in.

>>> 'kiwi' in fruits
True
>>> 'apple' in fruits
False

We can use the evaluation of such expressions in conditions:

>>> if 'apple' in fruits:
...    print("Let's bake a pie!")
... else:
...    print("Oops. No apples.")
...
Oops. No apples.

or

>>> if 'kiwi' in fruits:
...    print("Let's bake kiwi tarts!")
... else:
...    print("Oops. No kiwis.")
...    
Let's bake kiwi tarts!

This works the same with numbers or with mixed-type lists.

>>> some_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> 5 in some_primes
True
>>> 4 in some_primes
False

or

>>> mixed = (42, True, 'tobacconist', 3.1415926)
>>> 42 in mixed
True
>>> -5 in mixed
False

We can also check to see if some substring is within a string.

>>> "quick" in "The quick brown fox..."
True

So, we can see that the Python keyword in can come in very handy in a variety of ways.

Getting the index of an element in a sequence

Sometimes we want to know the index of an element in a sequence.

For this we use .index() method. This method takes some value as an argument and returns the index of the first occurrence of that element in the sequence (if found).

>>> fruits = ['kumquat', 'papaya', 'kiwi', 'lemon', 'lychee']
>>> fruits.index('lychee')
4

However, this one can bite. If the element is not in the list, Python will raise a ValueError exception.

>>> fruits.index('frog')
Traceback (most recent call last):
  File "/Library/Frameworks/.../code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
ValueError: 'frog' is not in list

This is rather inconvenient, since if this were to occur when running your program, it would crash your program! Yikes! So what can be done? Later on in this textbook we’ll learn about exception handling, but for now, here’s a different solution: just check to see if the element is in the list (or other sequence) first by using an if statement, and then get the index if it is indeed in the list.

>>> if 'frog' in fruits:
...     print(f"The index of frog in fruits is "
...           f"{fruits.index('frog')}")
... else:
...     print("'frog' is not among the elements in the list!")

This way you can avoid ValueError.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).