Add an object to a python list

后端 未结 4 1588
傲寒
傲寒 2021-01-07 17:38

I am trying to add an object to a list but since I\'m adding the actual object when I try to reset the list thereafter, all the values in the list are reset. Is there an act

4条回答
  •  爱一瞬间的悲伤
    2021-01-07 17:45

    You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

    mylist[:]
    

    Example:

    >>> first = [1,2,3]
    >>> second = first[:]
    >>> second.append(4)
    >>> first
    [1, 2, 3]
    >>> second
    [1, 2, 3, 4]
    

    And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

    >>> first = [1,2,3]
    >>> second = first
    >>> second.append(4)
    >>> first
    [1, 2, 3, 4]
    >>> second
    [1, 2, 3, 4]
    

    Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

提交回复
热议问题