I'm getting an error for a piece of python code I wrote that shouldn't
This is the function I wrote and the input I gave it.
#turn list of ints into set, remove val from set, and return the length of the set without val.
def foo(nums,val):
sett = set(nums)
sett_without_val = sett.remove(val)
return len(sett_without_val)
print(foo([3,2,2,3],3))
sett should be {3,2} sett_without_val should be {2} and len(sett_without_val) should be 1. I'm not supposed to get this error:
TypeError: object of type 'NoneType' has no len()
I thought it had something to do with the remove method I used, so I used discard instead and still got the exact same error message.
CodePudding user response:
remove()
method of set
is changing it in-place, so
sett_without_val = sett.remove(val)
returns None
and assign it to the variable,
working code is
def foo(nums,val):
sett = set(nums)
sett.remove(val)
return len(sett)
print(foo([3,2,2,3],3))
output:
1
Explanation:
1. [3, 2, 2, 3]
2. after set(): {3, 2}
3. after .remove(3): {2}
4. after len(): 1
CodePudding user response:
Sett.remove(val) does not return anything.
Try this
def foo(nums,val):
sett = set(nums)
sett.remove(val)
return len(sett)