Python index of string in list | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.