Reputation: 2825
I think I'm getting an error because the range of the list is reduced during iteration of the loop. I have 95 nested lists within a large list mega4
, and I'm trying to delete some strings with if and else. The list ufields
consist of 18 strings.
>>> for i in range(len(mega4)):
... for j in range(len(mega4[i])):
... for f in ufields:
... if (f in mega4[i][j]) is False:
... mega4[i].remove(mega4[i][j])
... else:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: list index out of range
The fourth line is basically asking if each element within mega4[i]
has each strings within ufields
, how can I remove the mega4[i][j]
in this case?
Edit:
I followed comments below and tried building a new list but this one does not seem to work
>>> mega5 = []
>>> for i in range(len(mega4)):
... for f in ufields:
... mega5.append([x for x in mega4[i] if f in x is True])
len(mega5)
is larger than len(mega4)
whereas it should be the same.
Upvotes: 0
Views: 39
Reputation: 27869
Simpler way:
result = [[sub for sub in item if sub] for item in mega4]
Your way wasn't working because you were editing list while iterating over it.
Upvotes: 1
Reputation: 49803
Depending on how ufields
is defined, you could eliminate the innermost loop by using if mega4[i][j] in ufields
.
Instead of modifying mega4
within this loop, you could build up a list of what elements you want to eliminate, and then do the actual elimination afterwards (looping over your list of candidates instead of mega4
itself).
Upvotes: 1