Question about Pass-by-object-reference?
malaclypse2 at gmail.com
Wed Jul 23 01:06:08 CEST 2014
On Tue, Jul 22, 2014 at 6:17 PM, fl <rxjwg98 at gmail.com> wrote:
> Thanks for your example. I do not find the explanation of [:] on line. Could you
> explain it to me, or where can I find it on line?
It's pretty hard to find if you don't already know what's going on.
First, you need to know that mylst[i:j] refers to a slice of the list
"mylist". Specifically, the items from the list starting with the
item at index i, up to but not including the item at index j. If you
leave the i off (e.g., mylist[:j]) that's a slice from the start of
the list up to (but not including) the j-th item. If you leave the
end position off, (e.g., mylist[i:]), that gets you the i-th item to
the end (including the last item). If you leave off both indexes from
the slice, you get back the entire contents of the list. So that's
what mylist[:] means.
Then you need to know that you can assign to the slice and it will
replace the old elements from the slice with the new ones. You can
see that defined here, in the docs (second item in the table under
"4.6.3. Mutable Sequence Types"):
So, when you so mylist[:] = [0,1] you're taking all of the contents of
the existing list, and replacing them with the contents of the list
[0,1]. That changes the existing list, it doesn't just assign a new
list to the name mylist.
More information about the Python-list