Why is the difference between this code

So I was give the task to write a code to get the union of two sets. And i wrote the the following 2 versions of codes.

Version 1

###### Set_Input ########

set_1=input().split(" ")
set_2=input().split(" ")

set_union=set_1+set_2

###### Set_Union_Logic ########

for i in set_union:
     if set_union.count(i)>1:
          set_union.remove(i)
print(set_union)

Version 2

###### Set_Input ########
set_1=input().split(" ")
set_2=input().split(" ")

set_union=set_1+set_2

###### Set_Union_Logic ########
for i in set_union:
     if set_union.count(i)>1:
         set_union= set_union.remove(i)

print(set_union)

Version 1 works fine but Version 2 gives me the following error

if set_union.count(i)>1:
AttributeError: 'NoneType' object has no attribute 'count'

Can any one explain why writing set_union= set_union.remove(i) in the loop causes this error.
Thanks in advance.

remove method of the list (that’s the actual data type of the set_union) returns None. As the returned result is assigned to the set_union, the set_union is actually None after the first iteration when if condition is True.

1 Like

Can you explain it in simple English please. I am new to Python :sweat_smile:

Method (or function) not always returns something, sometimes it just makes side-effect, without returning anything.

For example in set_1=input().split(" ") the split method does return the list with split string. remove method of the list however doesn’t return anything, because it changes the original list. When function or method in python doesn’t return anything explicitly it returns the None.

Nothing Python specific though :wink:
Functions in all coding languages will just execute whatever code you write into them. If this code doesn’t contain a return-value, they will not return anything (or something random) and in both cases, if you assign the function-call to a variable, this will take on whatever the return value is.
For built-in functions you don’t write yourself, you have to look up what their return-value is.