Search code examples
pythonlistindexing

Throwing index out of range during pop operation in python list


I am trying to sort only the positive integers in a list and insert them before the negative integers and zero, if any. I do not want to change the order of the negative/zero elements.

This is the code I am writing but it throws an index error when I am trying to remove the positive elements from the original list once the positive are sorted in a different list.

enter code here #sortonlypositivenumbers 
def solve(n, nums):
 positive = []
 for i in range(n):
  if nums[i] > 0:
   positive.append(nums[i])
  positive.sort()
 for i in range(n):
  if nums[i] > 0:
   nums.pop(i)
 nums = positive + nums
return nums

arr = list(map(int, input("Enter array separated by spaces.").split()))
length = len(arr)
print(solve(length, arr)) 

The output shows: IndexError: list index out of range for the statement if nums[i]>0 in second for loop


Solution

  • As pointed out by John Gordon, calling nums.pop(i) removes the ith element of nums, making it shorter. Since n is the initial length of nums, the for loop continues iterating past the new (shorter) length of nums and thus produces the index out of range error.

    To avoid this issue, you can solve the problem with a single loop through the list where you divide the values into positive and non-positive values, sort the positives, and then concatenate the two lists to get your desired output (note that you no longer need the length as an input to the function):

    def solve(nums):
        positives, non_positives = [], []
        for num in nums:
            if num > 0:
                positives.append(num)
            else:
                non_positives.append(num)
        positives.sort()
        return positives + non_positives