Posts

Showing posts with the label Python(built-ins)

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

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