1

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
kyrenia
  • 5,431
  • 9
  • 63
  • 93
  • The .add("test") call adds "test" to the set, but the function itself returns None. You should not be assigning new_set, instead put the assignment and the .add() call on different lines. i.e. set_to_add_to.add("test") is all you need. – Jacob H Feb 25 '16 at 18:50

2 Answers2

4

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]
Community
  • 1
  • 1
Garrett R
  • 2,687
  • 11
  • 15
  • 1
    As OP is new to Python, you may want to add that *all* functions return *something*, but *something* is None if `return` is omitted – cat Feb 25 '16 at 19:52
1

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

ml-moron
  • 888
  • 1
  • 11
  • 22