Find a Number in Python List

This tutorial will discuss about a unique way to find a number in Python list.

Suppose we have a list of numbers, now we want to find the index position of a specific number in the list.

List provides a method index() which accepts an element as an argument and returns the index position of the element in the list. Also if the element does not exist in the list, then it will raise a ValueError error.

Therefore, we should always encapsulate the index function call with a try except to handle the errors.

In the below example we will look for number 22 in the list. We will pass the number 22 in the index() method and it will give us the index position of that number in List.

Let’s see the complete example,

listObj = [32, 45, 78, 91, 17, 20, 22, 89, 97, 10]
number = 22

try:
    # Get index position of number in the list
    idx = listObj.index(number)
    print(f'Yes, {number} is present in the list at index : {idx}')
except ValueError:
    print(f'No, {number} is not present in the list.')

Output

Yes, 22 is present in the list at index : 6

Summary

We learned how to find a number in a Python List.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top