Q:

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

0

Syntax:

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

The index() returns zero-based index in the list of the first item whose value is equal to x and raises a ValueError if there is no such item.

Arguments:

  • x = item whose lowest index will be returned
  • start and end (optional) = used to limit the search to a particular subsequence of the list

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example Implementation

Scenario 1: retrieve index without providing optional arguments

-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

Scenario 2: retrieve index, providing the start 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
>>>

Scenario 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
>>>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now