How to Find an Index of an Element in Python

To find the index of a list element in Python, use the built-in index() function.

For example, let’s find the first string that equals "Bob" in a list of strings:

names = ["Alice", "Bob", "Charlie"]

names.index("Bob") # Returns 1

To find the index of a character in a string, use the index() method on the string.

For example, let’s find the first occurrence of the letter 'w' in a string:

"Hello world".index("w") # returns 6

How to Find the Index of a List Element in Python

You already saw a simple example of how to find the index of an element in a list:

names = ["Alice", "Bob", "Charlie"]

names.index("Bob") # Returns 1

The index() method works such that it returns the first occurrence of an element. In the above example, it returns 1, as the first occurrence of "Bob" is at the index 1.

But this method has a shortcoming. If the element you are searching for does not exist, an error is thrown.

For instance:

names = ["Alice", "Bob", "Charlie"]

idx = names.index("David")

Output:

ValueError: 'David' is not in list

You certainly don’t want your program to crash when searching for a non-existent value.

To overcome this issue, you should check that the element is in the sequence to begin with. To do this, use the in keyword.

For example:

names = ["Alice", "Bob", "Charlie"]

if "David" in names:
    idx = names.index("David")
else:
    print("Not found.")

Output:

Not found.

Now the above code no longer throws an error. The index search does not even start if the item is not there.

How to Find the Index of a String Character in Python

To find an index of a character in a string, follow the same procedure as finding an index in a list.

  • First check if the element is there.
  • Then find the index of it.

For instance:

sentence = "Hello world"

if "x" in sentence:
    idx = sentence.index("x")
else:
    print("Not found.")

Output:

Not found.

With strings, you can also search for larger substrings. For example, let’s find when a substring “wor” occurs in “Hello world”:

sentence = "Hello world"

substr = "wor"

if substr in sentence:
    idx = sentence.index(substr)
    print(idx)
else:
    print("Not found.")

Output:

6

This returns the starting position of the substring.

Conclusion

Use the index() method to find the index of an element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *