Find the index of an item given a list containing it in Python

Here, we will figure out how to discover the file of a thing given a list containing it in Python?

Python gives an inbuilt capacity called list(), which repeats through a list for a component inside the beginning and end scope of the list and returns the record of the predetermined component.

Syntax:

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

The list() returns a zero-based list in the list of the primary thing whose value is equivalent to x and raises a ValueError if there is no such thing.

Contentions:

  • x = thing whose most minimal file will be returned
  • start and end (discretionary) = used to constrain the hunt to a specific subsequence of the list

Example Implementation:

Situation 1: recover record without giving discretionary contentions:

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
>>> print(test_list.index('bangalore'))
0
>>> test_list_1 = [1,2,3,4,5]
>>> print(test_list_1.index(4))
3

Situation 2: recover record, giving the beginning and end limit:

-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
#finds the item 'bangalore' only within 0th to 3rd element in list and returns the index
>>> print(test_list.index('bangalore',0,3))
0


#finds the item 'bangalore' only within 1st to 3rd element in list and returns the index, and since the item 'bangalore' is not in that range, we get the exception
>>> print(test_list.index('bangalore',1,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'bangalore' is not in list
>>>

Situation 3: Demonstrating the ValueError:

Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> test_list = ['bangalore','chennai','mangalore','vizag','delhi']
>>> print(test_list.index('bhopal'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'bhopal' is not in list
>>>

Leave a Comment

error: Alert: Content is protected!!