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

后端 未结 4 802
臣服心动
臣服心动 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:13

    This is possible because x.append() is a method of list x that mutates the list in-place. There is no need for a return value as all the method needs to do is perform a side effect. Therefore, it returns None, which you assign your variable y.

    I think you want to either create a copy of x and append to that:

    y = x[:]
    y.append(7)
    

    or assign y the result of a list operation that actually creates a new list:

    y = x + [7]
    

提交回复
热议问题