How to get the index of a list in python
- 2021-07-06 11:20:17
- OfStack
1. index method
list_a= [12,213,22,2,32]
for a in list_a:
print(list_a.index(a))
Results: 0 1 2 3 4
If there are no duplicates in the list, then index is fine. What if there are duplicates in the list?
list_a= [12,213,22,2,2,22,2,2,32]
for a in list_a:
print(list_a.index(a))
Results: 0 1 2 3 3 2 3 3 8 < br > < br >
Obviously, the result is not what you want! ! ! So let's look at the second method >
2. enumerate method, which tuples elements in the list
list_a= [12,213,22,2,2,22,2,2,32]
print(list(enumerate(list_a)))
Results:
[(0, 12), (1, 213), (2, 22), (3, 2), (4, 2), (5, 22), (6, 2), (7, 2), (8, 32)]
This solves the problem of duplicate elements in the list,
ps: The following python returns the index of a value in the list
list = [5,6,7,9,1,4,3,2,10]
list.index(9)
out:3
You can also return the index of the maximum value in the list
list.index(max(list))
Minimum value index
list.index(min(list))
Summarize