简体   繁体   中英

Can someone explain why this function returns None?

I've been trying to figure out why this function is returning None every time I run it, I would appreciate a lot if someone could explain my why.

x = set([1,2,3])

def inserta(multiconjunto, elemento):
   
   a = multiconjunto.add(elemento)
   
   return a

mc1 = inserta(x, 2)
print(mc1)

It returns none because set.add() returns None , the add() method modifies the set, it does not return a new set.

There's no reason to put such a simple operation inside your own function put if you insist you could do this:

x = set([1,2,3])

def inserta(multiconjunto, elemento):
   multiconjunto.add(elemento)

inserta(x, 2)
print(x)

if you want to return a new set for some reason then:

x = set([1, 2, 3])


def inserta(multiconjunto, elemento):
    new_set = set(multiconjunto)
    new_set.add(elemento)

    return new_set


mc1 = inserta(x, 5)
print(mc1)
print(x)

should do the trick. It outputs

{1, 2, 3, 5}
{1, 2, 3}

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