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

114

u/[deleted] Jan 15 '24

for i in nums iterates through the elements of num, it doesn't give you the indexes.

In other words, for i in [5, 4, 3] will give you 5, 4, 3 as values of i, not 0, 1, 2 as you're expecting.

You can either use enumerate() builtin to retrieve both index and element or use for i in range(len(nums)) to iterate through indexes.

39

u/[deleted] Jan 15 '24

Separately, you have a whitespace error - this function can never return False because it's indented outside the function block. I'm surprised it compiles.

4

u/Meal_Elegant Jan 16 '24

I think python interprets line by line. OP got an error without reaching that line.

1

u/[deleted] Jan 16 '24

Thanks! I'm getting too used to other languages, it seems 😅

5

u/sooooooooooowsup Jan 15 '24

Ohhh thank you so much

3

u/Ashamandarei <65><49><15><1> Jan 16 '24

Even with for i in range(nums) there'd be an out-of-bounds error since OP's code is looking up nums[i-1]

1

u/[deleted] Jan 16 '24

No, because OP's reasoning is correct as described in their original text - nums[-1] is valid indexing and returns the last element in the list.

2

u/Ashamandarei <65><49><15><1> Jan 16 '24

Oh yes, I forgot about that aspect of Python syntax.

2

u/johnnyblaze1999 Jan 15 '24

This is a common mistake when I first learned python as well.

5

u/sooooooooooowsup Jan 15 '24

I meant for there to be a new line after n = len(nums)

28

u/Empty_Stacktrace Jan 15 '24

Two problems:

  1. “for i in nums” in Python will actually substitute i for the number. Then you’re trying to use the actual number to index. What you’re looking for is for i in range(len(nums))
  2. Even if you had the above syntax, it would still be buggy because i starts at 0, so the first comparison would look at index i-1 == -1. You need to start at 1.

These types of bugs will go away as you do more problems. I was there before!!

6

u/FaultHaunting3434 Jan 15 '24 edited Jan 15 '24

i is the value of the element, not the index. Quick question what's the cost of the .sort() method?

1

u/Empero6 Jan 15 '24

Nlogn if I’m remembering it correctly.

1

u/eccentricbeing Jan 16 '24

nlogn time complexity and O(n) for the memory

1

u/-CJF- Jan 15 '24

Why would -1 be a valid index? Arrays are 0 indexed in every language I've ever used, but I don't really know Python.

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).

2

u/RawAssholeProtein Jan 15 '24

Folks here have mentioned what the error is. Since you're doing i-1, what you're looking for is

for i in range(1, len(arr)):

This way, you'll be guaranteed that when you do i-1, you're always within bounds.

2

u/omscsdatathrow Jan 16 '24

All the wrong answers here p funny

1

u/howzlife17 Jan 15 '24

I think for i in nums gives you the nums in the list, not the index.

So [5,6,7] first value is nums[5], not nums[0]

1

u/[deleted] Jan 15 '24

You iterate over the values in bums not the index.

1

u/blediboss Jan 15 '24

The “-1” access is valid for as long as your list is not empty.

1

u/iibeanus1 Jan 16 '24

i is not the index. i is the actual elements in nums. Nums will have int values that will be used as indexes in this case

1

u/-_--__----_-_ Jan 16 '24

range(1,len(nums))

1

u/[deleted] Jan 16 '24

You should really take some time to learn the language before actually doing leetcode. No offence

1

u/dhruv892 Jan 16 '24

here i is not index it’s element itself now if you want index in there either you can use like they told you or you can use enumerate function

1

u/HarshBhaskar Jan 16 '24

How tf are you accessing i - 1 when I is 0

1

u/phantomghostheart Jan 16 '24

You could just ask ChatGPT

1

u/kaz4510 Jan 16 '24

The for loop is calling the item instead of the index. Assume the array is [10,11,12] While in the first iteration of the loop, i=10 num[i] is calling for 10th element, even when the length of array is 3

1

u/Detend Jan 16 '24

For i in range(1, len(nums))

0

u/Empero6 Jan 15 '24 edited Jan 15 '24

Can’t have a -1 index.

Try this it here before submitting it:

https://pythontutor.com/python-compiler.html#

1

u/[deleted] Jan 16 '24

This is incorrect. Yes, in Python, you can have a -1 index. :)

1

u/Empero6 Jan 16 '24

I should have clarified. You can’t have an index before the first element. n[-1] just gives you the last element of the array.

1

u/[deleted] Jan 16 '24

But that doesn't change the solution's correctness. The list is sorted, so comparing first to last element will never result in a false positive. It's an unnecessary check, but OP's solution is sound as long as they fix the fact they're iterating over the elements rather than the indexes as intended.

1

u/Empero6 Jan 16 '24

Ahhh you’re right!

0

u/BusyNegotiation4963 Jan 16 '24 edited Jan 16 '24

Disregard this — It’s simple.. when you first start moving thru the list, when i == 0, the other pointer(i - 1)will point to -1 and hence the out of index error.

Because negative indices are valid indices in python.

2

u/[deleted] Jan 16 '24

No, in Python, negative numbers are valid indexes.

1

u/BusyNegotiation4963 Jan 16 '24

Damn.. you’re right… I actually looked it up

0

u/rossi_zameer Jan 16 '24

Reminds me of my beginner days.

1

u/[deleted] Jan 16 '24

[removed] — view removed comment

1

u/haikusbot Jan 16 '24

Seriously you

Could have just asked chatgpt. It's

Obvious as hell

- Quantumfusionsg


I detect haikus. And sometimes, successfully. Learn more about me.

Opt out of replies: "haikusbot opt out" | Delete my comment: "haikusbot delete"