Which of the following searches for an element in a list and returns its index?

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

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 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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python-Built-in-functions
python-list
python-list-functions
Practice Tags :
python-list
Read Full Article

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

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề