简体   繁体   中英

Why am I getting a "TypeError: object of type 'NoneType' has no len()" for this using the len function on a set?

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.

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

Sett.remove(val) does not return anything.

Try this

def foo(nums,val):
      sett = set(nums)
      sett.remove(val)
      return len(sett)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM