Python Find the Index of a Given Element in List: A Beginner Guide – Python Tutorial

By | December 10, 2019

Python list.index() function can allow us to locate the postion of elements in python list, which is very useful when you want to get the index of an element. In this tutorial, we will introduce to you on how to use this function in python.

python list.index() function tutorials and examples

Syntax

list.index(ele)

Where ele is an element in list, this function will return the first index of ele in list.

We will use some examples to show you how to use this function.

Create a python list

params = ['-m', 'rgb', '-m', '-i', 'demo.png']

There are some elements in python list params.

Get index of -m

postion_m = params.index('-m')
print(postion_m)

The index is: 0

From the result we can find: there are two -m in params, however, params.index(‘-m’) only return the index of the first ‘-m‘.

Get the index of -t

postion_t = params.index('-t')
print(postion_t)

Before running this code, we have known that -t is not in params. Run it, you will get error:

postion_t = params.index(‘-t’)
ValueError: ‘-t’ is not in list

which means if you are getting the index of an element from a python list, you must concern this element may not  in python list, you should handle this exception.

Handle ValueError

Here is an example:

try:
    postion_t = params.index('-t')
    print(postion_t)
except ValueError as e:
    print(-1)

Run this code, you will get -1.

To know more about how to handle exception in python, you can read:

Understand Python Exception Handling: Try, Except and Finally for Python Beginners – Python Tutorial

Leave a Reply