Possible Duplicate:
What is the difference between slice assignment that slices the whole list and direct assignment?
I don't have money for school so I am teaching myself some Python whilst working shifts at a tollbooth on the highway (long nights with few customers). (BTW: Coursera should be translated to all languages...)
I have read here that if I have a list l
:
l = ['a', '', 'b']
and I want to filter out empty strings like so:
l = [c for c in l if c]
or like so:
l = filter(lambda x: x, l)
it is advisable to do this instead:
l[:] = ... # either method 1 or method 2 above
not to "lose" the reference to the first l
, especially in case other variables were pointing to it.
My question:
Why is it that
l[:]
denotes "the contents ofl
" in this case, allowing specifically reassignment to the "same"l
, when elsewhere I think of it as a "same size slice", conveniently creating a copy of l for me?Did I misunderstand how to use the
l[:]
for same-list-reassignments completely?
I thought that if I had an l
and I asked for a l[:]
, the latter was an actual copy of the original l
?
Reference: "Learning Python" -> There are a variety of ways to copy a list, including using the built-in list function and the standard library copy module. Perhaps the most common way is to slice from start to finish
Thanks!