In this Python tutorial, we will discuss how to get the index of an element in a Python List with various approaches using some built-in functions with some demonstrative examples.
To find the index of an element in a Python list, we can use various methods. List comprehension can be utilized as [i for i, x in enumerate(our_list) if x == ‘element’], where ‘element’ is the item we’re searching for. The index() method directly returns the index with our_list.index(‘element’). Using enumerate(), we can iterate as for i, x in enumerate(our_list) if x == ‘element’: print(i). With filter(), use next(i for i, x in filter(lambda ix: ix[1] == ‘element’, enumerate(our_list))). For a for loop and while loop, iterate and check each element.
Methods to get the index of an element in Python list
There are six different methods to get index of elemnet in Python list:
- List comprehension.
- Using index()
- Using enumerate()
- Using filter()
- Using for loop
- Using while loop
Let’s see them one by one using some illustrative examples:
Method 1: Find the index of an element in Python List using list comprehension
- We can use Python List Comprehension to get a list of all the indices for a specific element’s occurrences in a List.
- We can obtain the index values, or positions, of all instances of a given item in the List using List comprehension.
Syntax:
[exp for items in iterator if condition]
Example: Let’s take an example and check to get the index of an element in Python List using list comprehension.
new_list = [62,84,29,82,29,29,11,29]
print ("Input list : " ,new_list)
new_result = [i for i in range(len(new_list)) if new_list[i] == 29]
print ("Indexes at which item 29 is present: ",new_result)
Output: In the following given code first, we created a list in Python and then used the list comprehension method to iterate the values of the list and set the condition if new_list[i] == 29] then it will return the index values of that specific numbers.
Input list : [62, 84, 29, 82, 29, 29, 11, 29]
Indexes at which item 29 is present: [2, 4, 5, 7]
Here is the implementation of the following given Python code:
This is how to get the index of element in Python List using list comprehension.
Method 2: Get the index of an element in Python List using index() function
- An index() is a built-in function in Python. The element is passed as an argument and the index is returned by this function. We may determine the index of an entry in a list in Python by using this function.
- This function takes two main parameters and the range of places within which the search is to be conducted is represented by the optional start and finish parameters.
Syntax:
list.index(element, start, end)
Name | Description |
---|---|
element | This parameter specifies the element you’re searching for in terms of the index. |
start | The index which we want to be searched. |
end | This is an optional parameter to end the search. |
Example: Let’s take a list in Python and check the index of an item using index() function.
Country_name = ["U.S.A", "Germany", "China"]
# Searching for “Germany”
print("The input country is present at: ", Country_name.index("Germany"))
Output: In the following given code first, we will create a list and then use the list.index() function and within this function, we passed the item name which we want to be searched.
The input country is present at: 1
Here is the Screenshot of the following given code:
We can get the index of an element in Python List using an index() funtion.
Method 3: Get index of element in Python List using enumerate() function
- To get the index of an element in a Python list using the enumerate() function, we can iterate over the list and compare each element with the target value.
Example: Let’s take an example and check the index of an element in Python List using enumerate() with a target element.
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
target_city = "Chicago"
for index, city in enumerate(cities):
if city == target_city:
print("Index of Chicago in the list:", index)
break
else:
print("City not found in the list.")
Output: If the item matches target item (in this case, “Chicago”), it prints the index of the item and breaks out of the loop in Python.
Index of Chicago in the list: 2
Here is the Screenshot of the following given code
In this example, we have understood how to get the index of an element in Python List using enumerate.
Method 4: How to get the index of an element in Python List using filter() and lambda function.
- Based on the lambda function specified in the filter() method filters the given list in Python. Each list element will be supplied to the function along with the necessary items, which will be filtered depending on the function’s condition.
- To obtain the indexes for the specified element in the list, let’s utilize the filter() method.
Example: Here we will take an example and check how to get the index of an element in Python List using filter() and lambda function.
new_vales = [78,23,17,17,89,56,17]
print("Input list: ", new_vales)
new_result = list(filter(lambda m: new_vales[m] == 17, range(len(new_vales))))
print("Indexes for items 17 : ", new_result)
Output: The lambda function checks if the element at index m in the list in Python is equal to 17.
Input list: [78, 23, 17, 17, 89, 56, 17]
Indexes for items 17 : [2, 3, 6]
You can refer to the below Screenshot
This is how to get the index of an element in Python List using a filter() with lambda function.
Method 5: Get index of element in list Python using for loop
- A for loop is used to iterate over the range of indexes in the Python list. The range function generates a sequence of numbers starting from 0 up to (but not including) the length of the list in Python, which is determined by len() function.
Example: Let’s take a Python list and iterate over it to get the index of an element in Python List using for loop.
Cities_of_USA = ["NewYork", "NewYork", "California", "Florida", "Washington", "NewYork"]
emp_list = []
for m in range(0, len(Cities_of_USA)) :
if Cities_of_USA[m] == 'NewYork' :
emp_list.append(m)
print("Input list ", Cities_of_USA)
print("Indexes for items NewYork : ", emp_list)
Output: The implementation of the code is mentioned below:
Input list ['NewYork', 'NewYork', 'California', 'Florida', 'Washington', 'NewYork']
Indexes for items NewYork : [0, 1, 5]
This is how we can get the index of an element in Python List using for loop.
Method 6: Python list index index of an element using a while loop.
- A while loop to iterate through the list in Python, comparing each element with the target element.
- If a match is found, the loop breaks, and the index of the found element is printed. If the loop completes without finding the element, a message indicates that the element is not in the Python list.
Example: Suppose we have a list in Python and we want to find the index of a specific element using a while loop
states = ["California", "Texas", "Florida", "New York", "Illinois"]
target_state = "Texas"
index = 0
found = False
while index < len(states):
if states[index] == target_state:
found = True
break
index += 1
if found:
print("Index of Texas:", index)
else:
print("Texas is not in the list.")
Output: This script will search for the item in the Python list and print its index if found.
Index of Texas: 1
Here is the implementation of the following given code:
This is how to get the index of an element in Python List using a while loop.
Conclusion
To get the index of an element in a Python list can be achieved through six methods mentioned above, each catering to different needs and scenarios. Whether it’s the straightforward index() method, the versatile list comprehension, the classic for or while loops, or using enumerate() and filter() for more complex situations.
Python provides a variety of tools to efficiently locate elements within a list. Choosing the right method depends on the specific requirements of our task and our familiarity with Python’s functionalities.
You may also like to read the following Python tutorials:
- How to insert item at end of Python list
- How to get string values from list in Python
- Python List reverse() method
- How to get unique values from a list in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.