Suppose that I write a list:
foo=[1,2,3,4,5,6,7,8,9,1]
When I try to find out the index of 1
in foo
, it comes out to be 0. But I wanted to find the index of the 1
at the last ( it’s expected index is 9 ) so I wrote this simple code that would give me all the indexes of all the items in the list:
for i in foo: print(foo.index(i))
The result is:
0 1 2 3 4 5 6 7 8 0
Notice that the last 1
in foo also has an index of zero according to the above iteration.
Now I try to delete the list item with an index 9 by using:
del foo[9]
and the last1
gets deleted even though the iteration proved that it has an index 0!
Why is this happening?
Advertisement
Answer
When you use the index()
method it returns you the first instance of occurrence of the searched item.
Have a look at this
>>> a = [5, 4 , 1 , 3 , 1 , 2] >>> a.index(1) 2
This will not change no matter what you do and how many times you iterate. You can instead use
for index, item in enumerate(foo): print(index)