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

后端 未结 4 799
臣服心动
臣服心动 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条回答
  •  Happy的楠姐
    2021-01-11 11:07

    The y is None because the append() method doesn't return the modified list (which from your code you are expecting).

    So you can either split the statement,

    y = x.append(7)
    

    into

    x.append(7)
    y = x
    

    OR use,

    y = x + [7]
    

    The second statement is more cleaner and creates a new list from x.

    Just a note: Updating y won't make any updates in x as in the first statement it does. If you want to avoid this use copy.copy

提交回复
热议问题