
Hello, I'm Francis, a beginner programmer from Ghana, West Africa. I was wondering why the list .index() method doesn't return negative indices as well as well as positive indices. Although ambiguity will make it difficult to implement, in certain cases, it would be useful if it could return the negative index. For instance, if one creates an if statement that checks whether an element is the last item in a list as follows: listy = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if listy.index(10) == -1: print("Monty Python") I understand that the same effect can be achieved with the index notation - as in if listy[-1] == 10: print("Monty Python") - but the way that came naturally to me was to use the .index method rather than index notation, and it took a very long time for me to figure out why my code was not working(mostly because I'm a beginner). So do what you will, I guess.:)

index is meant to return the index of the first match it finds in the list from the beginning, it's most simpless implementation is: ``` for i, v in enumerate(self): if v == value: return i throw ValueError(f"Value '{value}' is not in list") ```` if you want the negative index, just subtract the list's length from the returned index: ``` res = listy.index(10) - len(listy) ```

On 30/01/21 3:27 am, Francis O'Hara Aidoo wrote:
listy = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if listy.index(10) == -1: print("Monty Python")
Although ambiguity will make it difficult to implement,
The difficulty isn't just with implementation, it's with *specification*. How is it supposed to know when you want a negative index without reading your mind? -- Greg

On Fri, 29 Jan 2021 at 14:37, Francis O'Hara Aidoo <kofiohara@gmail.com> wrote:
I understand that the same effect can be achieved with the index notation - as in if listy[-1] == 10: print("Monty Python") - but the way that came naturally to me was to use the .index method rather than index notation, and it took a very long time for me to figure out why my code was not working(mostly because I'm a beginner). So do what you will, I guess.:)
Another issue here is that indexing and the list.index method are not meant to be equivalent. In particular, the list.index method has to test all the elements in your list before it finds the value you are looking for, while indexing will just look up at the position you asked for, which is much faster for long lists (especially since you are looking at the last element in the list). In general, you shouldn't be using list.index if you already know the index you are looking for.
Best, E
participants (4)
-
Evpok Padding
-
Francis O'Hara Aidoo
-
Greg Ewing
-
William Pickard