0

So, here it is my problem. I'm trying to go over a nested list and delete some elements, according to a condition. The problem is that, whenever one element is deleted, this changes the length of the list which, in turn, creates the error:

IndexError: list index out of range

This is my code:

a = [[[1] * 2 for i in range(n)] for j in range(p)]
     for y in range(p):
        for x in range(n):
            if len(a[y]) > 1:
                if a[y][x][1] == 1:
                    if random.random() < s:
                        del a[y][x]

With s being just a number between 0 and 1. Because I want to make sure that every list has, at least, 1 value, I'm putting the if len(a[y]) > 1 part. I think I can understand the issue, the issue being that the length of the list is changing and, therefore, the position changes as well. Does anyone know a simple way to overcome this issue?

GWasp
  • 51
  • 6

1 Answers1

0

You need something like a

continue;

or

break;

statement (as for example in Java) that will stop your loop and prevents it to count too far.

So you can only delete one element in each inner loop. After the break; or the continue; you can iterate trough the list again with new list length to delete the second, third.. element if neccessary.

philszalay
  • 423
  • 1
  • 3
  • 9