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

16    Asked by grace_5975 in Python , Asked on Apr 13, 2021
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?

Answered by Grace

If you are facing attributeerror: 'nonetype' object has no attribute eror then 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]]]

Your Answer

Interviews

Parent Categories