Skip to content

Latest commit

 

History

History
44 lines (31 loc) · 717 Bytes

find_index_of_element_in_python.md

File metadata and controls

44 lines (31 loc) · 717 Bytes

How to find index of an element in python?

You can find index of an element by using the index() method. That method returns the first occurence of the element in a list. If it doesn't exists returns an error.

Example 1

my_list = ['foo', 'bar', 'nothing', 'something', 'foo']
my_list.index('bar')
  • output:
1

Example 2

my_list = ['foo', 'bar', 'nothing', 'something', 'foo']
my_list.index('foo')
  • output:
0

Example 3

my_list = ['foo', 'bar', 'nothing', 'something', 'foo']
my_list.index('thing')
  • output:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'thing' is not in list