Reputation: 2929
I don't understand the result of the code below. Why is the result None
?
m = {(1,2):1.0, (5,4):0.5, (3,4):0.75}
print(m.clear())
result: **None**
But if I write as
m.clear()
print(m)
result : **{}**
I have other result.
Upvotes: 1
Views: 84
Reputation: 1121584
You are printing the return value of m.clear()
, which returns None
. It returns None
because the .clear()
method clears the dictionary in place.
By convention, any method on a default Python type that alters the mutable structure in-place, returns None
. The same applies to list.sort()
or to set.add()
, for example.
Your second sample does not print the return value of m.clear()
. It prints the empty dictionary after you cleared it.
Upvotes: 4
Reputation: 71400
print(m.clear())
prints the value returned by the call m.clear()
. print m
prints the object m
; clearly two very different things, and so it's unsurprising that they produce different output.
The documentation for dictionary types simply says of clear
:
Remove all items from the dictionary.
That's what it does. It's not documented as returning anything, while all the documentation for all the methods that do return something are explicit about what they return (usually methods that alter a collection only return None
). So there's no reason to expect it to return anything.
Upvotes: 4