Skip to content

Python index of string in list | Example code

  • by

Use the index() method to get the index value of the string in a list. You can get a single index value from this method. to get the all strings index value use for-loop.

Get the index of items in the list syntax.

list.index(element, start, end)

Example find the index of a string in a list of strings python

Simple example code.

list1 = ["foo", "bar", "baz"]

print(list1.index("baz"))

Output: 2

Get all index of string index

list1 = ["foo", "bar", "baz"]

for x in list1:
    print(x, list1.index(x))

Output:

Python index of string in list

Another method:

Get first list index containing sub-string

list1 = ['abc', 'day', 'ghi']


def get_index(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
            return i
    return -1


print(get_index(list1, 'abc'))

Output: 0

Do comment if you have any doubts and suggestions on this Python index list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading