How to Use List index() Method in PythonPython Basics


The index() method returns the index where a substring exists in the string (if found).

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

list1 = ['MIT', 'CIT', 'Yale','UCI','123',321]

print("the index value of MIT is: ", list1.index('CIT'))

print("the index value of MIT is: ", list1.index('123'))

print("the index value of MIT is: ", list1.index('Yale'))

print("the index value of MIT is: ", list1.index(321))

Output:

the index value of MIT is:  1
the index value of MIT is:  4
the index value of MIT is:  2
the index value of MIT is:  5

Syntax

list.index(sub)

Parameters

Name Description
sub Substring to be searched in the string.

Return Value

It returns the index location of the searched substring and throws an exception if no substring is found.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us