Where in a Python list

Where in a Python List? Let’s Find Out This Item [Simple Tutorial]

A common problem in Python is to find out where in a list a specific item is. There are a few ways to do that.

To know where in a Python list a specific item is you can use the list index() method that returns the index of the item if the item is in the list. Otherwise it raises a ValueError exception. Another way to find the position of an item in a list is by using the linear search algorithm.

So, let’s start coding!

How Do You Find the Position of an Item in a Python List?

Python lists provide the index() method that:

  • Returns the index of an item in the list.
  • Raises a ValueError exception if the item is not in the list.

Let me show you how it works…

fruits = ['orange', 'apple', 'banana']
print(fruits.index('orange'))

[output]
0

The index() method returns 0 because that’s the index of the string we are looking for inside the list.

Note: remember that the value of the first index in a Python list is zero.

Here is what happens if the string we look for doesn’t exist in the list…

print(fruits.index('pineapple'))

This time the Python interpreter raises a ValueError exception because the string we are looking for doesn’t exist in the list.

Traceback (most recent call last):
  File "where_in_list.py", line 4, in <module>
    print(fruits.index('pineapple'))
ValueError: 'pineapple' is not in list

Makes sense?

Let’s continue…

Using Linear Search to Get the Index of an Item in a Python List

Another way to find where a value is in a list is by using linear search.

With linear search you start at the beginning of the list (index zero) and you keep increasing the index until you find an item that matches the value you are looking for.

Let me explain you with some Python code…

def linear_search(search_value, values):
    for i in range(len(values)):
        if values[i] == search_value:
            return i
    return -1

We have defined a Python function called linear_search that takes two arguments: the value to search for and the actual list.

Using the range and len functions we go through every item in the list starting from the index zero and we verify if any item matches the value we are looking for.

If we find an item that matches what we are searching for we return the index of that item. Otherwise we return -1.

Here are a few examples of execution.

print(linear_search('orange', fruits))

[output]
0

The function has found the string ‘orange’ at index zero.

print(linear_search('pineapple', fruits))

[output]
-1

This time the algorithm has not found the string ‘pineapple’ in the list and it returns -1.

Using Linear Search and Enumerate to Find Where an Item is in a Python List

Here is something useful to know…

We can simplify the definition of the linear_search function we have created before.

To do that we can use the Python enumerate function.

In the previous implementation of the linear search we have generated indexes in the for loop using the range and len functions.

Let’s see how we can do that with the enumerate function.

def linear_search(search_value, values):
    for index, value in enumerate(values):
        if value == search_value:
            return index
    return -1

Can you see how much cleaner is the code?

There are definitely a lot less brackets that usually make code harder to read.

Run this on your machine and confirm it works in the same way as the code without enumerate.

Here is how this for loop works with enumerate…

At every iteration the enumerate function returns index and value for each item in the list. In this way we don’t have to manually generate the index the way we have done before.

Here is what you get when you pass our list to the enumerate function.

print(enumerate(fruits))

[output]
<enumerate object at 0x102e292c0>

We get back an enumerate object. To see something more useful we have to convert this object into a list.

print(list(enumerate(fruits)))

[output]
[(0, 'orange'), (1, 'apple'), (2, 'banana')]

Can you see now how the for loop can access index and value for items in the list at every iteration?

How to Find Where an Item is in a List If It Appears Multiple Times

And what happens if the item we are looking for has duplicates in the list?

Let’s test the index() method first…

Update the list so that the string ‘orange’ appears twice and then retrieve the index of ‘orange’ from the list.

fruits = ['orange', 'apple', 'banana', 'orange']
print(fruits.index('orange'))

[output]
0

The result doesn’t change compared to the scenario in which the string ‘orange’ only appeared once in the list.

The list index() method only returns the index of the first occurrence of a specific item in a list.

Is there a way to get back both indexes?

I would like to get back 0 and 3 in this example.

Let’s update the linear search function to return a list of indexes in case the value we are looking for is in the list one or more times.

Otherwise we return -1 as already done before.

def linear_search(search_value, values):
    found_indexes = []
    for index, value in enumerate(values):
        if value == search_value:
            found_indexes.append(index)
    
    if len(found_indexes) > 0:
        return found_indexes
    else:
        return -1

We have applied the following code changes:

  • Define an empty list found_indexes that will contain the list of indexes in case an item is found in the list.
  • Append each index identified to the found_indexes list.
  • Return the found_indexes list if it’s not empty. Otherwise return -1.

Time to test this code…

fruits = ['orange', 'apple', 'banana', 'orange']

print(linear_search('orange', fruits))

[output]
[0, 3]

print(linear_search('pineapple', fruits))

[output]
-1

Nice!

We got back the expected results.

How Do You Check if an Item is in a Python List?

This last section is not about finding the exact position of an item in a list but it’s a simple way to verify if an item is part of a list.

This can be very useful when you just need to know if an item is in a list and you don’t need the position of that item in the list.

The Python in operator allows to find out if an item is in a list or not. It returns True if the item is in the list and False if the item is not in the list.

Want to see how the in operator works?

Let’s use the Python shell to do that.

>>> fruits = ['orange', 'apple', 'banana', 'orange']
>>> 'orange' in fruits
True
>>> 'pineapple' in fruits
False

Makes sense?

The values True and False are booleans…

I have another tutorial if you want to learn more about Python booleans.

Conclusion

We have covered a few ways to get the position of an item in a list and while doing that we have used several Python constructs:

  • List index() method
  • Linear search algorithm
  • For loops
  • Custom functions
  • Enumerate function
  • In operator

And now it’s your turn!

Practice the use of lists and keep improving your Python programs!

Leave a Reply

Your email address will not be published.

How to Import a Python Function fro...
How to Import a Python Function from Another File