This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: index doesn't change while looping through same elements in a list
Type: behavior Stage: resolved
Components: Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Dennis Sweeney, Tugberk
Priority: normal Keywords:

Created on 2022-03-22 15:09 by Tugberk, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg415785 - (view) Author: Tk44 (Tugberk) Date: 2022-03-22 15:09
Let us define a list where there are some duplicate elements. If we loop through that list as "for i in my_list" and print the index by my_list.index(i); the index doesn't change.

e.g.

my_list = [1,1,1,1,3]
for elm in my_list:
   print(my_list.index(elm))

==output==
0
0
0
0
4

This occurs where elements are of type string as well. Of course this can be overcome by using enumerate(); however I think this is a wrong behavior.
msg415804 - (view) Author: Dennis Sweeney (Dennis Sweeney) * (Python committer) Date: 2022-03-22 18:27
The help text says this:

    >>> help(list.index)
    Help on method_descriptor:
    
    index(self, value, start=0, stop=9223372036854775807, /)
        Return first index of value.
        
        Raises ValueError if the value is not present.

Emphasis on *first* index. Example:

>>> L = [0, 10, 20, 33, 0, 10]
>>> L.index(10)
1
>>> L[5]
10
>>> L.index(L[5]) # the same meaning as L.index(10)
1

In your code, when elm has the value 1, it's just the value 1; there's no extra information carried along about where that 1 came from. If elm == 1, then my_list.index(elm) means the same as my_list.index(1).

I'd suggest taking any further questions to either StackOverflow or https://discuss.python.org/c/users/

Thanks for the concern, but I'm closing this as "not a bug". Changing this behavior now would be backwards-incompatible and break lots of people's code.
History
Date User Action Args
2022-04-11 14:59:57adminsetgithub: 91250
2022-03-22 18:27:30Dennis Sweeneysetstatus: open -> closed

nosy: + Dennis Sweeney
messages: + msg415804

resolution: not a bug
stage: resolved
2022-03-22 15:09:35Tugberkcreate