iteration - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: iteration (/thread-30508.html) |
iteration - d8a988 - Oct-23-2020 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])
RE: iteration - scidam - Oct-23-2020 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_listIf the list become empty, the while-loop will terminate. RE: iteration - jefsummers - Oct-24-2020 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] |