Elements in a Python list are stored based on their index positions. Lists in Python provides an index(arg)
method to get the index position of an element within a list.
In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this article for Python List Index Method, we’ll explore how to use the index(arg)
method to obtain the index position of an element in a list.
index
Method
Python List Scenario 1 – Use Index to Get Element
We can use an element’s index position to retrieve it from the list. This is useful when we know the index of an element we want to access.
Scenario 2 – Use Element to Get Index
Use index(arg)
method – The index(arg)
method can be used to find the index of a specific element within a list
Python Index Method Syntax
- The
index()
method is used on list objects, following this syntax:
list.index(element, start, end)
element
– The element we want to search in the list to get its index position.start
(optional) – This is an optional parameter. This specifies the starting index for the search.- If this parameter is not given , then search will start from the first element (i.e. index
0
) in the list.
- If this parameter is not given , then search will start from the first element (i.e. index
end
(optional) – This is an optional parameter. This specifies the ending index for the search.- If this parameter is not given, then search includes all elements (up-to the last index) in the list.
- return value
- If the searched element is found in the list, then this method returns positive index position of that element
- If searched element is not present in the list, then it will return
ValueError
.
Program – Index of Element in List Python
# Index of Element in List
shbytes_list = ["DataScience", "Azure", "AWS", "Python", 14, 15, 16]
print(shbytes_list)
y = shbytes_list.index("Python") # search for element 'Python' in list
print(y)
y = shbytes_list.index(15) # search for element 15 in list
print(y)
In this program, we have defined a list referenced by the variable shbytes_list
. Here, we are using index(arg)
method without specifying the start and end indices, so the search begins from the first element (index 0
) and goes to the last element in the list.
Output – Example Program – Index of Element in List Python
['DataScience', 'Azure', 'AWS', 'Python', 14, 15, 16]
3
5
From the output, 3
is returned for index position of element Python
and 5
is returned for index position of element 15
.
Program – Index of Element in List with Start Index
# index of element, start search from given index in list
shbytes_list = ["DataScience", "Azure", "AWS", "Python", 14, 15, 16]
print(shbytes_list)
y = shbytes_list.index("AWS", 1) # search 'AWS' start from index 1
print(y)
Here, we define the same list and use the index(arg)
method with a start index but without an end index. The search for the element will start from given start index (i.e. index 1) in the list and will end at the last element in the list.
Output – Example Program – Index of Element in List with Start Index
['DataScience', 'Azure', 'AWS', 'Python', 14, 15, 16]
2
From the output, 2 is returned for index position of element ‘AWS’.
Program – Index of Element in List with Start and End Index
# index of element, start search from given index and search upto end index in list
shbytes_list = ["DataScience", "Azure", "AWS", "Python", 14, 15, 16]
print(shbytes_list)
y = shbytes_list.index("AWS", 1, 3) # search 'AWS', start index 1, end index 3
print(y)
y = shbytes_list.index(14, 1, 5) # search 14, start index 1, end index 5
print(y)
This program uses the index(arg)
method with both start and end indices. The search for the element will start from index 1 and ends at the specified end index.
Output – Example Program – Index of Element in List with Start and End Index
['DataScience', 'Azure', 'AWS', 'Python', 14, 15, 16]
2
4
2
is returned for index position of element AWS
and 4
is returned for index position of element 14
.
Program – Error: Element Not Present in List
# Error - when element not present in list
shbytes_list = ["DataScience", "Azure", "AWS", "Python", 14, 15, 16]
print(shbytes_list)
y = shbytes_list.index("Java") # search 'Java' in the given list
print(y)
Output – Example Program – Error: Element Not Present in List
Traceback (most recent call last):
File "D:-index-method-list.py", line 35, in <module>
y = shbytes_list.index("Java")
^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: 'Java' is not in list
In this case, the searched element Java
is not in the list, so a ValueError
is raised. ValueError: 'Java' is not in list
.
Program – Error: Element Not Present Within Start and End Index
# Error - element not present within start and end index
shbytes_list = ["DataScience", "Azure", "AWS", "Python", 14, 15, 16]
print(shbytes_list)
y = shbytes_list.index(14, 1, 3)
print(y)
Here, we attempt to search for element 14
from start index 1
to end index 3
. Although 14
is in the list at index 4
, it is outside the specified start and end range, causing an error.
Output – Example Program – Error: Element Not Present Within Start and End Index
Traceback (most recent call last):
File "D:-index-method-list.py", line 28, in <module>
y = shbytes_list.index(14, 1, 3)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: 14 is not in list
Element 14
is outside the start and end range, so a ValueError
occurs.
list.index()
Custom Implementation of To implement similar functionality as the index()
method, we can use a loop to iterate through the list and compare each element to the search value.
def custom_index(elements_list, element, start=0, end=None):
if end is None:
end = len(elements_list)
for i in range(start, end):
if elements_list[i] == element:
return i
raise ValueError(f"{element} is not in list")
course_list = ['Java', 'Python', 'Power BI', 'Machine Learning']
index = custom_index(course_list, 'Python')
print(index) # returns: 1
Summary
In this article, we explored the Python index()
method for lists, including its syntax, parameters, and how to handle errors when the element is not found within specified indices. The index()
method is essential for Python list manipulation, providing an efficient way to get element positions based on their values.
Code snippets and programs related to Python List Index Method, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
Q: What happens if the searched element is not in the list? How can we handle this scenario?
If the searched element is not present in the list, the index()
method raises a ValueError
. To handle this error, we can use a try-except block.
course_list = ['Python', 'ML', 'AI', 'Power BI']
try:
index_of_java = course_list.index('Java')
except ValueError:
print("Element not found in the list")
In this example, since element 'Java'
is not present in the course_list
, a ValueError
is raised, and the message “Element not found in the list” is printed.
index()
method, and how does it impact performance on large lists?
Q: What is the time complexity of the The index()
method has a time complexity of O(n), where n
is the number of elements in the list. This is because the method needs to scan through the entire list to find the element. index()
method return the very first occurrence of the element in the list. In case of very large lists, this can be slow if the element is near the end or not present at all.
Example: If we have to look for a element in a large list of a million elements and the element is near the end or not in the list, the index()
method will have to iterate through most or all of the list elements to determine the result, leading to slower performance.
index()
method case-sensitive?
Q: Is the Yes, the index()
method is case-sensitive. It means that 'java'
and 'Java'
would be considered different elements.
course_list = ['Python', 'java', 'Java', 'Power BI']
index_of_java = course_list.index('java') # Return index 1 for 'java'
index_of_java = course_list.index('Java') # Return index 2 for 'Java' (capital J)
In this example, 'java'
and 'Java'
are found at different indices because the method is case-sensitive.
index()
handle this situation?
Q: What happens if the list contains elements of different types? How does The index()
method can handle lists with different types of elements, but it will only return the index of an element that matches the specified type.
course_list = [100, 'Python', 23.33, 'Power BI', "23.33"]
print(course_list.index(23.33)) # Returns 2, matches 23.33 with its type at index 2
print(course_list.index("23.33")) # Returns 4, matches "23.33" with its type (str) at index 4
In this example, the index()
method correctly identifies the index of elements of different types in the course_list
.
list.index()
and list.find()
in Python?
Q: What is the difference between There is no list.find()
method in Python. The find()
method is used in strings, not lists.
list.index()
method is used to find the index of an element in a liststr.find()
is used to find the index of a substring in a string.- Unlike
list.index()
,str.find()
returns-1
if the substring is not found, rather than raising an exception.
Related Topics
- Understanding Lists in Python: A Comprehensive GuideLists in Python List is a core datatype in Python. Lists are sequences used to store elements (collection of data). Lists are similar to Arrays but are of dynamic size. It means the size of the list can be increased or decreased as we add or remove elements from the list. Understanding Python Lists: A…
- How to Create List in Python | Python List Creation Methods ExplainedList is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…
- How to Access List Elements by Index in Python (with Example Programs)Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
- Python List Index Method Explained with Examples | Get Element Position in ListElements in a Python list are stored based on their index positions. Lists in Python provides an index(arg) method to get the index position of an element within a list. In the previous article How to Access List Elements by Index, we learned how to access a list element using its index position. In this…
- Append Elements to List – Python | Add Elements with Append MethodIn Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…