How to find the index or indexes of an item in a list in Python

 

A simple answer to this is using string function index(),
>>> l = ['a','b','c']
>>> l.index('b')
1
The offical document states:

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

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.


The caveat follows

The index() method of the list object is so inefficient when your list becomes way to big. It checks every element from the start until it finds the element or to the end. When you don't know roughly the place of your searching element in such a large list, you should consider another data structure to avoid this overhead.  

If you do know the rough place where you could find the match, you should restrict the searching range by using start and end parameters, such as list.index(l, 100_000_000, 100_000_100).


How to return all the indexes of an item in a list

For this end, we could use a list comprehension

>>> l = ['a','b','d','e','a','f','g','a']

>>> [i for i, e in enumerate(l) if e=='a' ]




Comments

Popular posts from this blog

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

How to create a memory puzzle game with Python and Pygame (#005)

Introduction to multitasking with Python #001 multithreading (2020 tutorial)