Could you explain "[1, 2, 3].remove(2)" to me?

Ian Kelly ian.g.kelly at gmail.com
Thu Jun 25 14:37:24 EDT 2015


On Thu, Jun 25, 2015 at 12:14 PM, fl <rxjwg98 at gmail.com> wrote:
> Hi,
>
> I see a code snippet online:
>
> [1, 2, 3].remove(42)

I don't know where you pulled this from, but if this is from a
tutorial then it doesn't seem to be a very good one.

This constructs a list containing the elements 1, 2, and 3, and
attempts to remove the non-existent element 42, which will raise a
ValueError.

> after I modify it to:
>
> [1, 2, 3].remove(2)

This at least removes an element that is actually in the list, so it
won't throw an error, but the list is then discarded, so nothing was
actually accomplished by it.

> and
>
> aa=[1, 2, 3].remove(2)

This does the same thing, but it sets the variable aa to the result of
the *remove* operation. The remove operation, as it happens, returns
None, so the the list is still discarded, and the only thing
accomplished is that aa is now bound to None.

> I don't know where the result goes. Could you help me on the question?

You need to store the list somewhere before you start calling
operations on it. Try this:

aa = [1, 2, 3]
aa.remove(2)

Now you have the list in the variable aa, and the value 2 has been
removed from it.



More information about the Python-list mailing list