Can a method call be bound to the built-in "set ()"? (and why not?)

If I try:

mi_list = ['three', 'small', 'words']
mi_set = set(mi_list)
mi_set.remove('small')
print mi_set  

I get:

set(['three', 'words'])  

what i expect. If I try:

mi_list = ['three', 'small', 'words']
mi_set = set(mi_list).remove('small')
print mi_set

I get:

None

Why?

I suspect there is a key to this if I try to remove an item that is not there - for example, "large" - an error is reported:

KeyError: 'big'
+3
source share
6 answers

set.remove returns nothing (None).

Your code assigns the return value to the set.removevariable mi_set. Therefore mi_set is None.

+20
source

There is a general convention in python that methods that cause side effects return None. Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.

. , mi_set. :

mi_set2 = mi_set.remove('small')

: "mi_set2 mi_set". ! , . , None, python , , , , , .

. . , , sorted() reversed().

[ , list.pop - , . , .]

+8

:

>>> a = set(["a", "b", "c"])
>>> a = a.difference(["a"])
>>> print a
set(['c', 'b'])

, (- python, , None), .

+1

None? .remove,.add .. Return None:) . .

set , . , , :

class chain_set(set):
   def chain_add(self, x):
      newself = self.copy()
      newself.add(x)
      return newself

cs = chain_set([1,2,3,4])
cs.chain_add(5)
# chain_set([1, 2, 3, 4, 5])
cs.chain_add(7)
# chain_set([1, 2, 3, 4, 7])
cs.chain_add(7).chain_add(8)
# chain_set([1, 2, 3, 4, 7, 8])

: , cs ?

( ) ( ). , , , .

+1

, remove ?

0

remove , (, None). , remove:

Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = [1,2,3]
>>> s1 = set(lst)
>>> s1
{1, 2, 3}
>>> s2 = s1.remove(2)  # instead of reassigning s1, I save the result of remove to s2
>>> s1
{1, 3}  # *** 2 is not an element in the original set ***
>>> s2  # s2 is not a set at all!
>>> 

, , remove , , . , None, .

0
source

Source: https://habr.com/ru/post/1706459/


All Articles