How do you get the index of an element in a list in Python?

Python List index[]

In this tutorial, we will learn about the Python List index[] method with the help of examples.

The index[] method returns the index of the specified element in the list.

Example

animals = ['cat', 'dog', 'rabbit', 'horse']

# get the index of 'dog' index = animals.index['dog']

print[index] # Output: 1

Summary

  • Use the in operator with the index[] function to find if an element is in a list.

Did you find this tutorial helpful ?

Yes No

Python List index[]

index[] is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears.

Syntax:

list_name.index[element, start, end]

Parameters:

  • element – The element whose lowest index will be returned.
  • start [Optional] – The position from where the search begins.
  • end [Optional] – The position from where the search ends.

Returns:



Returns the lowest index where the element appears.

Error:

If any element which is not present is searched, it returns a ValueError

Example 1: Find the index of the element

Python3




# Python3 program for demonstration

# of list index[] method

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

# Will print the index of '4' in list1

print[list1.index[4]]

list2 = ['cat', 'bat', 'mat', 'cat', 'pet']

# Will print the index of 'cat' in list2

print[list2.index['cat']]

Output:

3 0

Example 1.1

Python3




# Python3 program for demonstration

# of index[] method

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

# Will print index of '4' in sublist

# having index from 4 to 8.

print[list1.index[4, 4, 8]]

# Will print index of '1' in sublist

# having index from 1 to 7.

print[list1.index[1, 1, 7]]

list2 = ['cat', 'bat', 'mat', 'cat',

'get', 'cat', 'sat', 'pet']

# Will print index of 'cat' in sublist

# having index from 2 to 6

print[list2.index['cat', 2, 6 ]]

Output:

7 4 3

Example 1.2

Python3




# Python3 program for demonstration

# of list index[] method

# Random list having sublist and tuple also

list1 = [1, 2, 3, [9, 8, 7], ['cat', 'bat']]

# Will print the index of sublist [9, 8, 7]

print[list1.index[[9, 8, 7]]]

# Will print the index of tuple

# ['cat', 'bat'] inside list

print[list1.index[['cat', 'bat']]]

Output :

3 4

Example 2: Index of the Element not Present in the List [ValueError]

Python3




# Python3 program for demonstration

# of index[] method error

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

# Return ValueError

print[list1.index[10]]

Output:

Traceback [most recent call last]: File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in print[list1.index[10]] ValueError: 10 is not in list

Example 3: When 2 arguments are Passed

When two arguments are passed in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins.

list_name.index[element, start]

Python3




# Python3 program for demonstration

# of index[] method

list1 = [6 , 8 , 5 , 6 , 1 , 2]

# Will print index of '3' in sublist

# having index from 1 to end of the list.

print[list1.index[6 , 1]]

Output:

3

Example 4: The end index passed as argument is not included

The third argument which is the end, itself is not included in the range from start to end, i.e the searching takes place from start to end-1 index.

Python3




# Python3 program for demonstration

# of index[] method

list1 = [6 , 2 , 14 , 8 , 9 , 10]

# return error as index '4' is not included in the range

# having index from 1 to 4.

print[list1.index[9, 1, 4]]

Output:

Traceback [most recent call last]: File "/home/3cbe5b7d0595ab3f8564f16af7a15172.py", line 9, in print[list1.index[9 , 1 , 4]] ValueError: 9 is not in list

Example 4.1

Python3




# Python3 program for demonstration

# of index[] method

list1 = [6 , 2 , 14 , 8 , 9 , 10]

# Will print index of '4' in sublist as now index '4' is included

# having index from 1 to 5.

print[list1.index[9, 1, 5]]

Output:

4




Article Tags :

Python

Python-Built-in-functions

python-list

python-list-functions

Practice Tags :

python-list

Read Full Article

Finding the index of an item given a list containing it in Python

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index [1] in Python?

Well, sure, there's the index method, which returns the index of the first occurrence:

>>> l = ["foo", "bar", "baz"] >>> l.index['bar'] 1

There are a couple of issues with this method:

  • if the value isn't in the list, you'll get a ValueError
  • if more than one of the value is in the list, you only get the index for the first one

No values

If the value could be missing, you need to catch the ValueError.

You can do so with a reusable definition like this:

def index[a_list, value]: try: return a_list.index[value] except ValueError: return None

And use it like this:

>>> print[index[l, 'quux']] None >>> print[index[l, 'bar']] 1

And the downside of this is that you will probably have a check for if the returned value is or is not None:

result = index[a_list, value] if result is not None: do_something[result]

More than one value in the list

If you could have more occurrences, you'll not get complete information with list.index:

>>> l.append['bar'] >>> l ['foo', 'bar', 'baz', 'bar'] >>> l.index['bar'] # nothing at index 3? 1

You might enumerate into a list comprehension the indexes:

>>> [index for index, v in enumerate[l] if v == 'bar'] [1, 3] >>> [index for index, v in enumerate[l] if v == 'boink'] []

If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:

indexes = [index for index, v in enumerate[l] if v == 'boink'] for index in indexes: do_something[index]

Better data munging with pandas

If you have pandas, you can easily get this information with a Series object:

>>> import pandas as pd >>> series = pd.Series[l] >>> series 0 foo 1 bar 2 baz 3 bar dtype: object

A comparison check will return a series of booleans:

>>> series == 'bar' 0 False 1 True 2 False 3 True dtype: bool

Pass that series of booleans to the series via subscript notation, and you get just the matching members:

>>> series[series == 'bar'] 1 bar 3 bar dtype: object

If you want just the indexes, the index attribute returns a series of integers:

>>> series[series == 'bar'].index Int64Index[[1, 3], dtype='int64']

And if you want them in a list or tuple, just pass them to the constructor:

>>> list[series[series == 'bar'].index] [1, 3]

Yes, you could use a list comprehension with enumerate too, but that's just not as elegant, in my opinion - you're doing tests for equality in Python, instead of letting builtin code written in C handle it:

>>> [i for i, value in enumerate[l] if value == 'bar'] [1, 3]

The XY problem is asking about your attempted solution rather than your actual problem.

Why do you think you need the index given an element in a list?

If you already know the value, why do you care where it is in a list?

If the value isn't there, catching the ValueError is rather verbose - and I prefer to avoid that.

I'm usually iterating over the list anyways, so I'll usually keep a pointer to any interesting information, getting the index with enumerate.

If you're munging data, you should probably be using pandas - which has far more elegant tools than the pure Python workarounds I've shown.

I do not recall needing list.index, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.

There are many, many uses for it in idlelib, for GUI and text parsing.

The keyword module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.

In Lib/mailbox.py it seems to be using it like an ordered mapping:

key_list[key_list.index[old]] = new

and

del key_list[key_list.index[key]]

In Lib/http/cookiejar.py, seems to be used to get the next month:

mon = MONTHS_LOWER.index[mon.lower[]]+1

In Lib/tarfile.py similar to distutils to get a slice up to an item:

members = members[:members.index[tarinfo]]

In Lib/pickletools.py:

numtopop = before.index[markobject]

What these usages seem to have in common is that they seem to operate on lists of constrained sizes [important because of O[n] lookup time for list.index], and they're mostly used in parsing [and UI in the case of Idle].

While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you're doing is the most direct usage of the tools provided by the language for your use-case.

Find index of element in list Python

In this short tutorial, learn to find the index of an element in a list in Python. We look at the code to achieve this with its pros and cons.

Before we delve into how you could find the index of an element in a list, we do a small recap on what lists are, in Python. However, in case you are already familiar with it, you can head straight to the Solution.

Python – Find Index or Position of Element in a List

To find index of the first occurrence of an element in a given Python List, you can use index[] method of List class with the element passed as argument.

index = mylist.index[element]

The index[] method returns an integer that represents the index of first match of specified element in the List.

You can also provide start and end positions of the List, where the search has to happen in the list.

Following is the syntax of index[] function with start and end positions.

index = mylist.index[x, [start[,end]]]

start parameter is optional. If you provide a value for start, then end is optional.

We shall look into examples, where we go through each of these scenarios in detail.

Example 1: Find Index of item in List

In the following example, we have taken a List with numbers. Using index[] method we will find the index of item 8 in the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87] item = 8 #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index]Run

Output

The index of 8 in the list is: 2

The element is present at 3rd position, so mylist.index[] function returned 2.

Example 2: Find Index of Item in List – start, end

In the following example, we have taken a List with numbers. Using index[] method we will find the index of item 8 in the list. Also, we shall pass start and end. index[] function considers only those elements in the list starting from start index, till end position in mylist.

Python Program

mylist = [21, 8, 67, 52, 8, 21, 87] item = 8 start=2 end=7 #search for the item index = mylist.index[item, start, end] print['The index of', item, 'in the list is:', index]Run

Output

The index of 8 in the list is: 4

Explanation

mylist = [21, 8, 67, 52, 8, 21, 87] ----------------- only this part of the list is considered ^ index finds the element here 0 1 2 3 4 => 4 is returned by index[]

Example 3: Find Index of Item – Item has multiple occurrences in List

A Python List can contain multiple occurrences of an element. In such cases, only the index of first occurrence of specified element in the list is returned.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 52 #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index]Run

Output

The index of 52 in the list is: 3

The element 52 is present two times, but only the index of first occurrence is returned by index[] method.

Let us understand how index[] method works. The function scans the list from starting. When the item matches the argument, the function returns that index. The later occurrences are ignored.

Example 4: Find Index of Item in List – Item not present

If the element that we are searching in the List is not present, you will get a ValueError with the message item is not in list.

In the following program, we have taken a list and shall try to find the index of an element that is not present in the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 67 #search for the item/element index = mylist.index[item] print['The index of', item, 'in the list is:', index]Run

Output

Traceback [most recent call last]: File "example.py", line 5, in index = mylist.index[item] ValueError: 67 is not in list

As index[] can throw ValueError, use Python Try-Except while using index[]. In the following example, we shall learn how to use try-except statement to handle this ValueError.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52] item = 67 try: #search for the item index = mylist.index[item] print['The index of', item, 'in the list is:', index] except ValueError: print['item not present']Run

Output

item not present

The item, whose index we are trying to find, is not present in the list. Therefore, mylist.index[item] throws ValueError. except ValueError: block catches this Error and the corresponding block is executed.

Summary

In this Python Tutorial, we learned how to find the index of an element/item in a list, with the help of well detailed examples.

Related Tutorials

  • Python – List of Strings
  • Python List of Lists
  • How to Access List Items in Python?
  • Python List without Last Element
  • How to Sort Python List?
  • How to Append List to Another List in Python? – list.extend[list]
  • How to Get the list of all Python keywords?
  • Python List of Dictionaries
  • Python List of Functions
  • Python – Check if Element is in List

Python: Get index of item in List

To find index of element in list in python, we are going to use a function list.index[],

list.index[]

Python’s list data type provides this method to find the first index of a given element in list or a sub list i.e.

Advertisements

list.index[x[, start[, end]]]

Arguments :

  • x : Item to be searched in the list
  • start : If provided, search will start from this index. Default is 0.
  • end : If provided, search will end at this index. Default is the end of list.

Returns: A zero based index of first occurrence of given element in the list or range. If there is no such element then it raises a ValueError.

Important Point : list.index[] returns the index in a 0 based manner i.e. first element in the list has index 0 and second element in index is 1.

Let’s use this function to find the indexes of a given item in the list,

Suppose we have a list of strings,

# List of strings list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

Now let’s find the index of the first occurrence of item ‘Ok‘ in the list,

elem = 'Ok' # Find index position of first occurrence of 'Ok' in the list index_pos = list_of_elems.index[elem] print[f'First Index of element "{elem}" in the list : ', index_pos]

Output

First Index of element "Ok" in the list : 1

As in the list.index[] we did not provided start & end arguments, so it searched for the ‘Ok‘ in the complete list. But returned the index position as soon as it encountered the first occurrence of ‘Ok‘ in the list.

But if searched item doesn’t exists in the list, then index[] will raise ValueError. Therefore we need to be ready for this kind of scenario. For example,

list_of_elems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok'] elem = 'Why' try: index_pos = list_of_elems.index[elem] print[f'First Index of element "{elem}" in the list : ', index_pos] except ValueError as e: print[f'Element "{elem}" not found in the list: ', e]

Output

Element "Why" not found in the list: 'Why' is not in list

As ‘Why‘ was not present in the list, so list.index[] raised ValueError.

Video liên quan

Bài mới nhất

Chủ Đề