0

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
San Okami
  • 11
  • 1

1 Answers1

2

The remove() method of a list performs an in-place modification of the list and returns None. Since Version 2 sets set_union to the return value, the next iteration tries to call a method of a None object, resulting in an error.

I should add that your split() is creating a list, so set_union = set_1 + set_2 is adding two lists together and you may have duplicate values. If you actually want a proper set of unique values, you may want set_union = set(set_1 + set_2) instead.

sj95126
  • 6,520
  • 2
  • 15
  • 34