I was working with list in python and I need to remove non-true values.
Can someone explain why here I get index out of range error:
for n in range(len(lst)-1): #index outside the range
if not bool(lst[n]):
lst.pop(n)
return lst
It is kind of work with while loop
def compact(lst):
while n < len(lst):
if not bool(lst[n]):
lst.pop(n)
n =1
print(n)
return lst
But in this case loop will skip some items.
function is called like:
compact([0, 1, 2, '', [], False, (), None, 'All done'])
CodePudding user response:
When you delete an element, all the elements after it renumber: the n 1
th element becomes n
th element, etc. But you progress to the next n
anyway. This is why you are skipping some elements.
In the first snippet, you pre-construct the list of indices to iterate over; but as the list shortens, some of the later indices will not exist any more.
In the second snippet, you compare with the actual length of the list on each iteration, so you never get an invalid index.
Also note that bool
is not needed whenever you are evaluating a condition, as it is implicitly applied in such a context.
In order to do this correctly, you have two choices:
iterate from end of the list backwards. If you delete an element, the elements in front of it do not get renumbered.
for n in range(len(lst) - 1, -1, -1): if not lst[n]: lst.pop(n)
using the
while
method, make sure to either incrementn
(movingn
closer to the end of the list), or delete an element (moving the end of the list closer ton
); never both at the same time. This will ensure no skipping.n = 0 while n < len(lst): if not lst[n]: lst.pop(n) else: n = 1
The third option is to avoid the index loop altogether, and do it more pythonically, generating a new list using a comprehension with a filtering condition, or filter
.
new_lst = list(filter(bool, lst))
or
new_lst = [e for e in lst if e]
or, if you really want to change the original list, replace its content like this:
lst[:] = filter(bool, lst)
CodePudding user response:
Index out of range error:
lst.pop(n)
This will pop element from the list but for n in range(len(lst)-1)
will still loop through the lst assuming same length as original.
To avoid this start loop from last index in reverse order so that even after pop values will still be present for indexes yet to be read.
def compact(lst):
for n in range(len(lst)-1,-1,-1):
if not bool(lst[n]):
lst.pop(n)
return lst
ls = [0, 1, 2, '', '',[], False, (), None, 'All done','']
print(compact(ls))
# Output:
# [1, 2, 'All done']