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

Question:

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?

Asked By: kyrenia

||

Answers:

The .add() method for sets always returns None, in the same way that the .append() list method returns None for example.

Answered By: K. Menyah

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]
Answered By: Garrett R
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.