How to add new value to a list without using 'append()' and then store the value in a newly created list?

后端 未结 4 809
臣服心动
臣服心动 2021-01-11 10:33

I have been trying this a lot.

>>> x = [4,5]
>>> y = x.append(7)
>>> print y
None
>>>print x
[4, 5, 7]

4条回答
  •  情深已故
    2021-01-11 11:10

    Because the function append() modifies the list and returns None.

    One of the best practices to do what you want to do is by using + operator.

    Let's take your example :

    >>> x = [4, 5]
    >>> y = x + [7]
    >>> x
    [4, 5]
    >>> y
    [4, 5, 7]
    

    The + operator creates a new list and leaves the original list unchanged.

提交回复
热议问题