Home > Net >  Python code throws error list out of range, even though the logic is same
Python code throws error list out of range, even though the logic is same

Time:07-12

1)

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i = 1
        while i < len(nums)-1:
            if nums[i]==nums[i-1] and nums[i]==nums[i 1]:
                del nums[i]
            else:
                i =1
        return len(nums)

The code above happens to work perfectly.

2)

class Solution:
        def removeDuplicates(self, nums: List[int]) -> int:
            n = len(nums)-1
            i = 1
            while i < n:
                if nums[i]==nums[i-1] and nums[i]==nums[i 1]:
                    del nums[i]
                else:
                    i =1
            return len(nums)

But the 2nd code throws this error :-

IndexError: list index out of range
    if nums[i]==nums[i-1] and nums[i]==nums[i 1]:

The logic behind both the codes happens to be same, in the first code we don't store the length of the list nums, instead we use it in while loop directly like while < len(nums) - 1

In the second code, we store the value of len(nums) in a variable n, and use it in a similar fashion in the while loop, while i < n - 1

I don't understand what's the difference between the two.

CodePudding user response:

Your two snippets are not identical.

Notice that the list is modified inside the loop with del nums[i], so its length changes.

In the first code, you access len(nums) every time you need it, so you always get the correct value of len(nums).

In the second code, when you do n = len(nums) - 1, the value of len(nums) - 1 at that time is assigned to the variable n. This variable isn't automatically updated when the value of len(nums) changes, so even after you delete elements of the list, n still has its original value.

  • Related