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)
CodePudding user response:
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}