Skip to content
Advertisement

Why does Python assign None if you add a variable to a set while assigning it

Instead of adding a variable to a set correctly, e.g.:

 set_to_add_to = set()
 set_to_add_to.add("test")

I just accidentally coded:

 set_to_add_to = set()
 set_to_add_to = set_to_add_to.add("test")

While I appreciate that this is not how you should add items to a set, it surprised me that the above resulted in set_to_add_to taking the value None. I couldn’t work out why that would happen: it seems analogous to int_variable = int_variable + 5, which works correctly.

Similarly:

 set_to_add_to = set()
 new_set = set_to_add_to.add("test")

results in new_set taking the value None — why is it not the case that "test" is added to set_to_add_to and then that assigned to new_set?

Advertisement

Answer

First of all, it is import to note all functions (including user-defined and built-in functions) return something. Usually, it is easy to see what a function returns by its return statement. In a function without a return statement, None is returned by default.

Now, for the rationale behind why some python commonly used functions return None.

In general, python functions that modify objects in place return None.

For example:

x = [4,3,7,8,2]
y = sorted(x) #y is now a sorted list because sorted returns a copy!
y = x.sort() # y is now None because x was sorted in place

A notable exception is the pop() function which returns the value being popped.

Check out this post for a more detailed explanation:

Is making in-place operations return the object a bad idea?

x = [4,3,7,8,2]
val = x.pop() 

#val = 2
#x = [4,3,7,8]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement