Reputation: 1928
I have a list of lists with None
's and I would like to delete the two lists so that data becomes empty. But for some reason it seems the for
loop is aborted after the first list is deleted, what am'I missing ?
data = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]
for i,d in enumerate(data) :
if None in d :
del data[i]
data
Out[128]: [[1531872000000, None, None, None, None, 0.0]]
# Expected result :
data
Out[130]: []
Thank you
Upvotes: 0
Views: 652
Reputation: 2522
x = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]
y = []
for i in x:
if None not in i:
y.append(i)
print(y)
y = [i for i in x if None not in i]
print(y)
[]
Upvotes: 1
Reputation: 35395
You should never delete elements from a list in an enumerate loop. Because once you delete data[0]
in the first iteration, the list itself id now modified and has only one element, so the next enumerate
does not return anything (it thinks it has already looped through all elements).
Better way to do this:
data = [x for x in data if None not in x]
Upvotes: 0
Reputation: 195408
You are deleting member of data array while you are iterating the same array. That's never good solution.
For removing members of data that contains None you can try this:
data = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]
data = [d for d in data if None not in d]
print(data)
Output:
[]
Upvotes: 1
Reputation: 555
data = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]
del data[:]
Output: []
Upvotes: -1