CodeBlessU
learn code with examples

Python Find Index of element

Use .index() method to find index of element in sequence.

Argument is mandatory.

If element is present multiple times, it returns index of first instance from start. If element is not present in sequence, it raises ValueError.

Syntax:
variable.index( x )
Return Value:
index
Use
  • len - How many elements?
  • .count() - How many times this element is present?
  • .index() - What is the index / position of this element?

ValueError: .index(x): x not in list

Why this error:

Are you trying to call .index() and not sure if element is present or not? Element must be present to find index.

Are you trying to find index of float (i.e. typecode 'f')? It might not work for float.

Solution:

Check if element is present using .count(), if its present, use .index().

List find index / position of element

# Example, List find index of an element.
a1 = [1, 2, 3, "Hi", 1.2, 3, 2, 2]
a1.index(1) # returns 0
a1.index(2) # returns 1

ValueError: x is not in list

# Example,
a1 = [1, 2, 3, "Hi", 1.2, 3, 2, 2]

print( a1.index(10) ) # raises ValueError: 10 is not in list

# Solution
if a1.count(10) > 0:
    print( a1.index(10) )
else:
    print("Element not found.")

Tuple find index / position of element

# Example, Tuple find index of an element.
a1 = (1, 2, 3, "Hi", 1.2, 3, 2, 2 )
a1.index(1) # returns 0
a1.index(2) # returns 1

ValueError: tuple.index(x): x not in tuple

# Example,
my_tuple = (1, 2, 3, "Hi", 1.2, 3)

print( my_tuple.index(10) ) # raises ValueError: tuple.index(x): x not in tuple

# Solution
if my_tuple.count(10) > 0:
    print( my_tuple.index(10) )
else:
    print("Element not found.")

Array find index / position of element

# Example, Array find index of an element.
import array

a1 = array.array('l', [1, 10, 100, 1, 10, 100, 1, 2, 3] )
position = a1.index(10) # assigns 1

ValueError: array.index(x): x not in list

# Example, Array find index raises ValueError
import array

a1 = array.array('l', [1, 10, 100, 1, 10, 100, 1, 2, 3] )
a1.index(-1) # returns ValueError
position = a1.index(0) # returns ValueError

In this page...

Copyright © All rights reserved.