Methods not related in Python set

I have a Python set consisting of several values, and I want to use a method chain as follows:

>>> f = {1, 2, 3} >>> g = f.copy().discard(3) >>> g >>> 

but g becomes empty. However, it works without chaining:

 >>> g = f.copy() >>> g {1, 2, 3} >>> g.discard(3) >>> g {1, 2} 

Can someone explain this behavior to me?

+5
source share
4 answers

When you execute g = f.copy().discard(3) , you store the return value of the "discard (3)" method in g. In this case, it does not return anything, but modifies the object. That is why it works in the second scenario.

+2
source

discard() discards the element in the set and returns None .

so when you assign

 g = f.copy().discard(3) 

it is equivalent

 h = f.copy() # now h = f g = h.discard(3) # g = None; h = {1,2} 

which leaves you with g = None .

+5
source

You can instead of fo f - {3} , because - on sets is a value that produces and does not change its inputs.

+1
source

This is because .discard returns None .

So, when you do g = f.copy().discard(3) , it creates a copy of f , discards the last element, and then returns None . Since the last thing to return is what is assigned to the variable, g ends with the value None .

0
source

All Articles