The index method in Python lists serves as a valuable tool when a user needs to determine the index of a specific item within a provided list. This method initiates its search from the very first element and persists until it locates the index of the element's first appearance.
Note: This method returns the position of only the first occurrence of the element and return a ValueError if the element is not found in the specified range.
Syntax of the index Method in Python List
Below is the syntax for the list index method:
Syntax:
list.index(elmnt, start, end)
Parameters:
- elmnt (Required) : This parament looks the elements to search for. It accepts any type of variable such as string , number , list, etc.
- start (Optional): It takes the value representing the position from where the user wants to start the search.
- end (Optional): This parameter takes a number value representing the position from where to end the search.
Returns:
The index function provides the location of the initial occurrence of a specified value. Should the element be absent, it raises a ValueError.
Examples of List index
Next, we will examine several instances of the list index function in Python.
Example 1: Find Position of an Element in a List
In this illustration, we will examine the functionality of the index method as it identifies the location of a specified element within a provided list.
Example
# given lists
num_list = [12, 13, 9, 10, 7, 2]
fruit_list = ['apple', 'banana', 'mango', 'banana', 'cherry', 'grapes']
# using the index() method
print("The index of 10 is:", num_list.index(10))
print("The index of 'cherry' is:", fruit_list.index('cherry'))
Output:
The index of 10 is: 3
The index of 'cherry' is: 4
Explanation:
In this instance, we have utilized the index function to determine the position of the first appearance of the designated elements within the provided lists.
Example 2: Find Position of an Element in a List from a Specified Starting Index
We will now examine an illustrative example to determine the index of a specific element within a provided list. However, instead of beginning the search from 0, we will define a custom starting point for the search process.
Example
# given lists
list_1 = [19, 11, 21, 16, 11, 15, 29]
list_2 = ['red', 'green', 'blue', 'yellow', 'purple', 'red', 'pink', 'orange']
# using the index() method
print("The index of 11 starting from index 3 is:", list_1.index(11, 3))
print("The index of 'red' starting from index 4 is:", list_2.index('red', 4))
Output:
The index of 11 starting from index 3 is: 4
The index of 'red' starting from index 4 is: 5
Explanation:
In this instance, we designated the starting index in the index function to locate the initial occurrence of the elements within the specified lists, beginning from that particular index.
Example 3: Find Position of an Element in a List between a Specified range
This illustration will demonstrate the utilization of the index method to determine the location of an item within a specified range of a particular list.
Example
# given lists
list_1 = ['red', 'blue', 'green', 'yellow', 'blue', 'white', 'black', 'grey', 'pink']
list_2 = [0, 1, 11, 4, 12, 5, 6, 3, 12, 11, 5, 7]
# using the index() method
print("The index of 'blue' between 2nd and 6th index is:", list_1.index('blue', 2, 6))
print("The index of 12 between 6th and 9th index is:", list_2.index(12, 6, 9))
Output:
The index of 'blue' between 2nd and 6th index is: 4
The index of 12 between 6th and 9th index is: 8
Explanation:
In this instance, we defined the initial and final indices to locate the specified elements within the provided lists, focusing on those particular ranges.
Example 4: Find Position an Element that is Not Present in the List
Let us now examine a scenario in which we will attempt to retrieve the index of an element that is absent from the specified list.
Example
# given list
list_1 = ['blue', 'red', 'green', 'yellow', 'orange', 'white', 'black', 'grey']
try:
# using the index() method
print("The index of 'pink' is:", list_1.index('pink'))
except ValueError:
print("'pink' is not present in the list")
Output:
'pink' is not present in the list
Explanation:
In the preceding illustration, we utilized a 'try…except' construct to manage ValueError exceptions. Within the 'try' segment, we invoked the index function to determine the position of a particular element in the specified list. Because the element in question was absent from the list, a ValueError was triggered, which was subsequently caught by the 'except' segment, resulting in a message being displayed for our benefit.
Conclusion
The index method in Python serves as a valuable function for locating a specific element within a list. It consists of three parameters, allowing users to specify both the starting and ending positions for the search of the element. This method is commonly utilized by developers to effectively handle and search for data within a list.
The index method in Python serves the purpose of locating the first occurrence of a specified value within a list or a string. This method returns the index of the initial instance of the value that you are searching for. If the value is not found, a ValueError is raised.
Syntax
list.index(element, start, end)
Parameters
- element: This is the item you want to find the index for.
- start (optional): This specifies the position in the list where the search begins. The default is 0.
- end (optional): This indicates the position in the list where the search stops. The default is the end of the list.
Example
fruits = ['apple', 'banana', 'cherry', 'apple']
index_of_banana = fruits.index('banana')
print(index_of_banana) # Output: 1
index_of_cherry = fruits.index('cherry', 1)
print(index_of_cherry) # Output: 2
In the example provided, the index of 'banana' in the list is determined to be 1, while 'cherry' is found at index 2 when starting the search from index 1.
The index function is utilized to locate a specific item within a list and yields the index (or position) of its first appearance.
- What will the index function produce if the specified element cannot be located in the list?
In the event that the specified element is absent from the list, Python will raise a ValueError.
- Does the index method provide the index for all instances?
No. The index method provides the index position solely for the initial instance of the specified element. It does not yield multiple index values.
- Is the index method sensitive to case when applied to strings?
Indeed, the index function is case-sensitive by default. This implies that when working with the string 'monday', it will be treated as distinct from 'Monday', which results in these two values being regarded as separate entities.
Example:
days = [Monday, Tuesday, Wednesday]
val = days.index("monday")
print (val)
If we attempt to search for 'monday', Python will trigger a ValueError, as it will be unable to locate the precise value.