Why is there no list.clear() method in python?

前端 未结 4 1316
长情又很酷
长情又很酷 2021-01-01 08:38

Inspired by this question.

Why is there no list.clear() method in python? I\'ve found several questions here that say the correct way to do it is one of the followin

4条回答
  •  难免孤独
    2021-01-01 09:34

    The question should be why clear was deemed necessary in the first place. The following works to clear any Python collection that I can think of.

    def clear(x):
        return type(x)()
    
    >>> s = {1, 2, 3}
    >>> s
    set([1, 2, 3])
    >>> s = clear(s)
    >>> s
    set([])
    >>> l = [1, 2, 3]
    >>> l
    [1, 2, 3]
    >>> l = clear(l)
    >>> l
    []
    

提交回复
热议问题