Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
iteration
#1
I am trying to remove the first item from a list at every iteration if when subtracted from the next number on the list will give a result that is equal or greater than 1.
The following code produces the right outcome but mixed with error messages.
How to fix my code so I get only the answer without the error messages?
nums = [0,1,3,4,6,8,10]
for i in range(len(nums)):
    if (nums[i]-nums[0] >=1):
        del(nums[0])
Error:
[0, 1, 3, 4, 6, 8, 10] if (my_list[i]-my_list[0] >=1): [1, 3, 4, 6, 8, 10] IndexError: list index out of range [3, 4, 6, 8, 10] [4, 6, 8, 10] Process finished with exit code 1
Reply
#2
The error was raised because the length of the list was changed. This is usually bad practice to iterate over changing list (using for-loop). However, I don't completely understand the problem. Are you always need to remove the first element of the list or you need to remove the previous element if the next is larger by 1?..
Try to rewrite the code using while loop, e.g.

index = 0
while index < len(your_list):
    # index += 1 etc.
    # remove items from your_list
If the list become empty, the while-loop will terminate.
Reply
#3
Just to speed things up a little, the while loop above can be abbreviated

while len(your_list):
as when the len is 0 the expression is equivalent to False

Also, list comprehension is fast, though does make it a bit harder to read

nums = [x for x in nums if x - nums[0] >1]
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020