[Tutor] insering into lists through slices
dyoo at hkn.eecs.berkeley.edu
Fri Jun 3 20:06:56 CEST 2005
On Fri, 3 Jun 2005, venkata subramanian wrote:
> I am a newbie to Python (that's very guessable).
> I simply fail to understand the semantics of the following piece of code.
> #assuming ls=[1,2,3,4]
> #then ls becomes
> >>> ls
> [1, 5, 6, 2, 3, 4]
> i would be happy to know how it works.
> Basically, ls[1:1] returns an empty list and assigning [5,6] to it,
> actually inserts the elements... but how?
Actually, this is a gotcha. Usually, when we are doing assignments (=),
the left hand side has to be a variable name. For example:
>>> x = 42
>>> def double(x):
... return x * 2
>>> double(3) = 42
SyntaxError: can't assign to function call
>>> 2**3 = 8
SyntaxError: can't assign to operator
So we're not allowed to just put anything on the left hand side, since
that wouldn't fit well with the concept of assignment.
When we're assigning, we're trying to bind some value to some name or
place or thing. The reason that we get those SyntaxErrors about in the
example above is because the left hand side wasn't describing a valid
place for storing things.
With that in mind, let's go back to:
ls[1:1] = [5,6]
This is a kind of assignment that Python does allow. It doesn't mean to
take the left hand side and evaluate it, but instead, it means to squeeze
the elements of the right hand side into the place described by the left
hand side. This is list slice assignment, and it's a special case.
(For the gory details on what is allowed on the right hand side of an
assignment, you can take a quick look at the Reference Manual:
but I wouldn't recommend focusing on it too much.)
Anyway, hope that makes some sense. Please feel free to ask more
More information about the Tutor