Index value in list and string start from 0

Python List index()

The list index() method helps you to find the first lowest index of the given element. If there are duplicate elements inside the list, the first index of the element is returned. This is the easiest and straightforward way to get the index.

Besides the built-in list index() method, you can also use other ways to get the index like looping through the list, using list comprehensions, enumerate(), filter methods.

The list index() method returns the first lowest index of the given element.

Syntax

list.index(element, start, end)

Parameters

ParametersDescription
elementThe element that you want to get the index.
startThis parameter is optional. You can define the start: index to search for the element. If not given, the default value is 0.
endThis parameter is optional. You can specify the end index for the element to be searched. If not given, it is considered until the end of the list.

Return Value

The list index() method returns the index of the given element. If the element is not present in the list, the index() method will throw an error, for example, ValueError: ‘Element’ is not in the list.

Example: To find the index of the given element.

In the list my_list = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’] , we would like to know the index for element C and F.

The example below shows how to get the index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F'] print("The index of element C is ", my_list.index('C')) print("The index of element F is ", my_list.index('F'))

Output:

The index of element C is 2 The index of element F is 5

Example: Using start and end in index()

In this example will try to limit searching for index in a list using start and end index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] print("The index of element C is ", my_list.index('C', 1, 5)) print("The index of element F is ", my_list.index('F', 3, 7)) #using just the startindex print("The index of element D is ", my_list.index('D', 1))

Output:

The index of element C is 2 The index of element F is 5 The index of element D is 3

Example: To test index() method with an element that is not present.

When you try to search for index in the list for element that is not present ,you will get an error as shown below:

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] print("The index of element C is ", my_list.index('Z'))

Output:

Traceback (most recent call last): File "display.py", line 3, in <module> print("The index of element C is ", my_list.index('Z')) ValueError: 'Z' is not in list

9. Lists¶

A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type. Lists and strings — and other things that behave like ordered sets — are called sequences.

Python – Start and End Indices of words from list in String

Given a String, our task is to write a Python program to extract the start and end index of all the elements of words of another list from a string.

Input : test_str = “gfg is best for all CS geeks and engineering job seekers”, check_list = [“geeks”, “engineering”, “best”, “gfg”]

Output : {‘geeks’: [23, 27], ‘engineering’: [33, 43], ‘best’: [7, 10], ‘gfg’: [0, 2]}

Explanation : “geeks” starts from index number 23 till 27, hence the result.

Input : test_str = “gfg is best for all CS geeks and engineering job seekers”, check_list = [“geeks”, “gfg”]



Output : {‘geeks’: [23, 27], ‘gfg’: [0, 2]}

Explanation : “geeks” starts from index number 23 till 27, hence the result.

Method #1 : Using loop + index() + len()

In this, loop is used to get each element from list. The index() gets the initial index and len() gets the last index of all the elements from list in the string.




# Python3 code to demonstrate working of
# Start and End Indices of words from list in String
# Using loop + index() + len()
# initializing string
test_str = "gfg is best for all CS geeks and engineering job seekers"
# printing original string
print("The original string is : " + str(test_str))
# initializing check_list
check_list = ["geeks", "engineering", "best", "gfg"]
res = dict()
for ele in check_list :
if ele in test_str:
# getting front index
strt = test_str.index(ele)
# getting ending index
res[ele] = [strt, strt + len(ele) - 1]
# printing result
print("Required extracted indices : " + str(res))

Output:

The original string is : gfg is best for all CS geeks and engineering job seekers

Required extracted indices : {‘geeks’: [23, 27], ‘engineering’: [33, 43], ‘best’: [7, 10], ‘gfg’: [0, 2]}

Method #2 : Using dictionary comprehension + len() + index()

In this, we perform tasks similar to the above function but the construction of the result dictionary is done using shorthand using dictionary comprehension.




# Python3 code to demonstrate working of
# Start and End Indices of words from list in String
# Using dictionary comprehension + len() + index()
# initializing string
test_str = "gfg is best for all CS geeks and engineering job seekers"
# printing original string
print("The original string is : " + str(test_str))
# initializing check_list
check_list = ["geeks", "engineering", "best", "gfg"]
# Dictionary comprehension to be used as shorthand for
# forming result Dictionary
res = {key: [test_str.index(key), test_str.index(key) + len(key) - 1]
for key in check_list if key in test_str}
# printing result
print("Required extracted indices : " + str(res))

Output:

The original string is : gfg is best for all CS geeks and engineering job seekers

Required extracted indices : {‘geeks’: [23, 27], ‘engineering’: [33, 43], ‘best’: [7, 10], ‘gfg’: [0, 2]}

Index value in list and string start from 0




Article Tags :
Python
Python Programs
Python string-programs

Python String index()

In this tutorial, we will learn about the Python index() method with the help of examples.

The index() method returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.

Example

text = 'Python is fun'
# find the index of is result = text.index('is')
print(result) # Output: 7

Find index of element in list Python

In this short tutorial, learn to find the index of an element in a list in Python. We look at the code to achieve this with its pros and cons.

Before we delve into how you could find the index of an element in a list, we do a small recap on what lists are, in Python. However, in case you are already familiar with it, you can head straight to the Solution.