List getting extended when assigned to itself

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Aug 25 00:03:22 EDT 2013


On Sat, Aug 24, 2013 at 8:52 PM, Krishnan Shankar
<i.am.songoku at gmail.com> wrote:
> Hi Python Friends,
>
> I came across an example which is as below,
>
>>>> var = [1, 12, 123, 1234]
>>>> var
> [1, 12, 123, 1234]
>>>> var[:0]
> []
>>>> var[:0] = var
>>>> var
> [1, 12, 123, 1234, 1, 12, 123, 1234]
>>>>
>
> Here in var[:0] = var we are assigning an entire list to the beginning of
> itself. So shouldn't it be something like,
>
> [[1, 12, 123, 1234], 1, 12, 123, 1234]
>
> It happens when we do the below,
>
>>>> var = [1, 12, 123, 1234]
>>>> var[0] = var
>>>> var
> [[...], 12, 123, 1234]
>>>>
>
> Literally var[0] = var and var[:0] = var almost meens the same. But why is
> the difference in output? Can anyone explain what happens when slicing
> assignment and direct assignment.

Are you sure they're almost the same?

>>> var[0]
1
>>> var[:0]
[]

One's a list and one is an integer. It's hard for them to be any more
different. var[0] means that you should be setting an element of the
list. var[:0] says you want to update a piece of the list, not an
element inside it.



More information about the Python-list mailing list