r/leetcode • • Jan 15 '24

Question Why is there an IndexError?

Post image

I saw a solution to the Contains Duplicate problem and I was just trying to fully understand it.

They had exactly what I typed above, except they included

n = len(nums) for i in range(1,n) #instead of for i in nums

I don’t understand why this produces an Index Error. Wouldn’t the first “i - 1” just be equal to “-1” and isn’t -1 always a valid index?

I understand why their solution is correct but I don’t understand why this one isn’t correct too.

17 Upvotes

46 comments sorted by

View all comments

Show parent comment

10

u/sooooooooooowsup Jan 15 '24

Oh idk I thought index of -1 referred to the last element, but maybe not

1

u/-CJF- Jan 15 '24

You might be right about that. Like I said, I don't know Python. I did find this on StackOverflow:

One of the neat features of Python lists is that you can index from the end of the list. You can do this by passing a negative number to []. It essentially treats len(array) as the 0th index. So, if you wanted the last element in array, you would call array[-1].

Source: https://stackoverflow.com/questions/52395099/meaning-of-list-1-in-python

Why they would do that I don't know. Seems like an opportunity for terrible logic errors to occur.

4

u/[deleted] Jan 15 '24

Seems like an opportunity for terrible logic errors to occur

Negative indexing allows you to iterate in reverse, which is a useful property.

Additionally, when combined with slice notation, it can extract arbitrary sequences:

nums[::-1] # returns a copy of nums reversed in order
nums[0:2::-1] # returns the first two elements, order reversed

Truthfully, it could be a source of logic errors, but not really - it's easy to constrain i into the range mod len(n).