How to Search for Elements in a Python List

In Python, to find the position of an element in a list, you can use the index method.

listname.index(element)

You provide the element you want to find as a parameter. This can be either a string or a numeric value.

How the index method works

The index method returns the position of the element.

  • If there are multiple occurrences, the index method only returns the position of the first occurrence from the left.
  • If there are no occurrences, the index method raises an error that needs to be handled as an exception.

    A Practical Example

    In a program, I have the following list:

    years = [2010, 2011, 2012, 2013, 2014]

    To find the position of the value 2013:

    print(years.index(2013))

    This command displays the position of the element in the list:

    3

    The position is the third (not the fourth) because the list index starts at zero, not one.

    So, the first element is at position zero, the second at position one, the third at position two, and the fourth (2013) at position three. And so on.

    Another Example of Searching in a List

    Similarly, you can search for an alphanumeric string in a list.

    In the following list, there are some city names:

    cities = ['Rome', 'Naples', 'Milan', 'Florence']

    To find the position of the string 'Milan', you write:

    print(cities.index('Milan'))

    This command displays the position of the element in the list:

    2

    And so on.

    What if the Element Doesn't Exist in the List?

    If you try to search for a non-existent element:

    print(cities.index('Bologna'))

    The command returns an error message:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: 'Bologna' is not in list

    Therefore, when searching for something in a list using the index method in Python, it's important to handle exceptions to manage possible errors.

    try:
    print(cities.index('Bologna'))
    except:
    print("element not found")

    When you search for a non-existent element, the exception is triggered and the message is displayed:

    element not found

    This way, you intercept and avoid displaying error messages in the program during the search.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Lists

    1. What is a list
    2. Extracting elements from a list
    3. Removing an element
    4. Adding elements
    5. How to count occurrences in a list
    6. How to search for an element in a list
    7. Sorting a list
    8. Reversing the order of a list
    9. List comprehension
    10. Nesting list
    11. How to convert a tuple into a list