Hello, readers! Hope you all are doing well. In this article, we will be focusing on the Different techniques to get the index of an element in a Python List.
So, let us get started.
What is a Python List?
A Python list is a data structure that plays the role of an Array efficiently. Moreover, a list stores elements in a dynamic manner and can be used to store elements of different types unlike, Arrays.
Thus, Lists can be considered as a better replacement for the Array data structure and can hold heterogeneous elements altogether.
How to get the index of an item in a Python List?
Having understood the working of Python List, let us now begin with the different methods to get the index of an item of the List.
Method 1: List Comprehension
Python List Comprehension can be used to avail the list of indices of all the occurrences of a particular element in a List.
Syntax:
Using List comprehension, we can get the index values i.e. position of all the occurrences of an item in the List.
Example:
Output:
Method 2: Using index[] method
Pythons inbuilt index[] method can be used to get the index value of a particular element of the List.
Syntax:
The startand endparameters are optional and represent the range of positions within which search is to be performed.
Unlike other methods, the index[] method returns only the index value of the first occurrence of the particular item in the list.
If the mentioned element is not present in the List, a ValueError exception is raised.
Example:
Output:
Method 3: Using enumerate[] function
Python enumerate[] method can also be used to return the index positions of all the occurrences of the particular element in the List.
Example:
Here, the enumerate[] method sets a counter which increments after every successful search of that particular item and returns the index value of it.
Output:
Conclusion
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question. Till then, Happy Learning!!
References
- How to get the index of an item in a Python List StackOverflow