1

I wanted to make a copy of a list in python while also removing one element:

x = [1,2,3]
a = list(x).remove(2)

While x was still [1,2,3] as expected, a was None instead of the [1,3] that I expected.

I get the expected behavior if I break line 2 into two lines:

x = [1,2,3]
a = list(x)
a.remove(2)

a is now [1,3] with x unmodified.

Why is this?

fdsa
  • 1,379
  • 1
  • 12
  • 27
  • In general `x = obj.method1().method2()` will call `method1` on `obj` and `method2` on the *return value* of `obj.method1()`. And the return value of `method2` will be what is assigned to the variable `x`. – poke Mar 29 '15 at 20:38

2 Answers2

4

.remove() method modifies the list itself, it does not return the modified list. For example:

x = [1, 2, 3]
x.remove(2)
print x

result:

[1, 3]

In general, most list methods modify the list in-place. There are built-ins for some methods (like sorted for .sort()) that return the modified list but there are none for .remove().

Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

If you do need to copy your list, there are several options, but I prefer:

x = [1, 2, 3]
y = x[:]
x.remove(2)
print x, y

this prints:

[1, 3] [1, 2, 3]
Scott
  • 6,089
  • 4
  • 34
  • 51
  • Why do you prefer that? – fdsa Mar 29 '15 at 20:51
  • Here is a link to a question asking how to clone a list. Of all of the options listed in the top answer, I feel that slicing, y = x[:], is the simplest (though not necessarily intuitive that you would be making a copy).http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – Scott Mar 29 '15 at 20:56