Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading