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

I tried a lot.

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

How is this possible?

When I try to save the values ​​in a new list y and print it, it will result in None , and also change the current list `x.

Is there any other way to do this in Python?

+7
python
source share
3 answers

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

One of the best ways to do what you want to do is to use the + operator.

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.

+4
source share

This is possible because x.append() is an x list method that mutates the list in place. There is no need for a return value, since the whole method must perform a side effect. Therefore, it returns None , which you assign to your y variable.

I think you want to either create a copy of x and add to it:

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

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

 y = x + [7] 
+4
source share

You can do

 x = [4,5] y = x + [7] # x = [4, 5] # y = [4, 5, 7] 
+2
source share