12 of 151 menu

The index method

The index method searches for an element in a list and returns the index of its first occurrence. In the first parameter, we specify the element we are interested in. In the second optional parameter, we specify the search start position, and in the third optional parameter, the search end position.

Syntax

list.index(what are we looking for, [start searching], [end of search])

Example

Let's find the position of the first occurrence of the element 'ab':

lst = ['ab', 'cd', 'ab', 'ef', 'ab'] print(lst.index('ab', 1, 3))

Result of code execution:

0

Example

Now let's set the positions for the start and end of the search:

lst = ['ab', 'cd', 'ab', 'ef', 'ab'] print(lst.index('ab', 1, 3))

Result of code execution:

2

Example

Let's look for the missing element:

lst = ['ab', 'cd', 'ab', 'ef', 'ab'] print(lst.index('xx'))

In this case, the method will return us an error:

ValueError: 'ab' is not in list

See also

  • function len,
    which returns the length of the list
  • method count,
    which returns the number of times an element occurs in a list
  • method insert,
    which adds an element to the list before the specified index
  • method pop,
    which removes an element by its index
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline