Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (20.3k points)

I have a 3D list in python like:

features= [ [[1,2,3],[1,2,3],[1,2,3]] ,None , [[1,2,3],[1,2,3],[1,2,3]],

        [[1,2,3],[1,2,3],[1,2,3]], None,None,[[1,2,3],[1,2,3],[1,2,3]] ]

I expect to see:

features=[ [[1,2,3],[1,2,3],[1,2,3]] ,[[1,2,3],[1,2,3],[1,2,3]],

               [[1,2,3],[1,2,3],[1,2,3]] ,[[1,2,3],[1,2,3],[1,2,3]] ]

When I try to remove None using the following code:

for i in range(len(features)):

if features[i]==None:

    features[i].remove()

It produces the error :

AttributeError: 'NoneType' object has no attribute 'remove'

If I try this:

for i in range(len(features)):

if features[i]==None:

    del features[i]

It produces the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Lastly, I tried this code:

for i in range(len(features)):

if features[i]==None:

    features[i]=filter(None,features[i])

It produced the error :-

TypeError: 'NoneType' object is not iterable

How can I fix this error?

2 Answers

0 votes
by (40.7k points)

You can try creating a list comprehension and only keep the values if the index is not None, it will keep your sub-lists intact like this:

features = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

>>> print features 

[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], None, None, [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

>>> print [f for f in features if f is not None]

[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]

0 votes
by (106k points)

To get rid of the error you can use the below-metioned code:-

features_x = list(filter(None, features)) 

print(features_x)

Browse Categories

...