how to find the position of an element in a list in Python

In this Python tutorial, we will learn how to find the position of an element in a list in Python. To find the position of an element in a list, we need to understand the concept of the index of the elements in a list.

Find the position of an element in a list in Python

In a list, there is a term called “index“, which denotes the position of an element. But here, the position does not start with one or first. In this concept of the index, the index starts with zero.

Let’s take an easy example to understand it.

new_list = ['h','p','l']

Here you can see three elements in this list.

‘h’ is at the very first position of the list. ‘p’ is at the second position of the list.



But if we say what is the index of the element ‘h’? Then the answer will be zero.

here the index of ‘p’ is 1 and index of ‘l’ is 2

So,

the position of an element = index of the element in the list +  1

Now we will see how to find the position of an element in a list in Python

Python Program to find out the position of an element in a list

new_list =['A','K','Q','J','2','3','4','5','6','7','8','9','10']
print(new_list.index('J'))

If you run this program the output will be:

$ python codespeedy.py
3

The above Python program is to find the index of an element in a list in Python

Now we will see how to find the position of an element in a list:

new_list =['A','K','Q','J','2','3','4','5','6','7','8','9','10']
print(new_list.index('J')+1)

Output:

$ python codespeedy.py
4

The position of ‘J’ is 4

Explanation of the program: Finding the index of an element in a list in Python

method used: index() method

syntax of the method: list_name.index(element)

In the index() method you have to pass the element whose index you are going to find.

Return value: This method returns the index value of the element.

 

Special note:

If you pass an element in index() method and the element is not in the list. Then the program will give you

'element' is not in list

Leave a Reply

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