AttributeError: 'NoneType' object has no attribute 'remove' issue
Question:
I want to remove certain values from a list if they are elements in a specified other list, as below. Ideally this would return list2 = ["e","f","g"], but instead it returns the above error as it seems once one of the elements is removed list1 becomes a None type variable…
list1 = ["a","b","c", "d", "e", "f", "g"]
list2 = ["a","b","c","d"]
for x in list1:
if x in list2:
list1 = list1.remove(x)
print(list1)
Answers:
The method list.remove()
is performed in place. So instead of:
list1 = list1.remove(x)
It should be like this:
list1.remove(x)
The complete code
The complete and working code should look as follows.
list1 = ["a", "b", "c", "d", "e", "f", "g"]
list2 = ["a", "b", "c", "d"]
temp = list1.copy()
for x in list1:
if x in list2:
temp.remove(x)
print(temp)
More explanations
Because list.remove()
is performed in place, it does not return anything, or in other words, it returns None
.
A simpler approach using list comprehension
As CrazyChucky pointed out, removing items from a list while iterating is not a good thing to do. You would have to make a copy of the list first before adding or removing items from the list. Or you can choose another option, which is to use list comprehension instead.
list1 = ["a", "b", "c", "d", "e", "f", "g"]
list2 = ["a", "b", "c", "d"]
print([i for i in list1 if i not in list2])
I want to remove certain values from a list if they are elements in a specified other list, as below. Ideally this would return list2 = ["e","f","g"], but instead it returns the above error as it seems once one of the elements is removed list1 becomes a None type variable…
list1 = ["a","b","c", "d", "e", "f", "g"]
list2 = ["a","b","c","d"]
for x in list1:
if x in list2:
list1 = list1.remove(x)
print(list1)
The method list.remove()
is performed in place. So instead of:
list1 = list1.remove(x)
It should be like this:
list1.remove(x)
The complete code
The complete and working code should look as follows.
list1 = ["a", "b", "c", "d", "e", "f", "g"]
list2 = ["a", "b", "c", "d"]
temp = list1.copy()
for x in list1:
if x in list2:
temp.remove(x)
print(temp)
More explanations
Because list.remove()
is performed in place, it does not return anything, or in other words, it returns None
.
A simpler approach using list comprehension
As CrazyChucky pointed out, removing items from a list while iterating is not a good thing to do. You would have to make a copy of the list first before adding or removing items from the list. Or you can choose another option, which is to use list comprehension instead.
list1 = ["a", "b", "c", "d", "e", "f", "g"]
list2 = ["a", "b", "c", "d"]
print([i for i in list1 if i not in list2])