Florent
Florent

Reputation: 1928

How to delete nested lists with None in Python?

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

Answers (4)

zamir
zamir

Reputation: 2522

x = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]

Imperative approach

y = []

for i in x:
    if None not in i:
        y.append(i)

print(y)

List comprehension

y = [i for i in x if None not in i]
print(y)

Output:

[]

Upvotes: 1

Hari Menon
Hari Menon

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

Andrej Kesely
Andrej Kesely

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

Rob
Rob

Reputation: 555

data = [[1531785600000, None, None, None, None, 0.0], [1531872000000, None, None, None, None, 0.0]]

del data[:]

Output: []

Upvotes: -1

Related Questions