Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52963 > unrolled thread

Re: List getting extended when assigned to itself

Started byBenjamin Kaplan <benjamin.kaplan@case.edu>
First post2013-08-24 21:03 -0700
Last post2013-08-24 21:03 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: List getting extended when assigned to itself Benjamin Kaplan <benjamin.kaplan@case.edu> - 2013-08-24 21:03 -0700

#52963 — Re: List getting extended when assigned to itself

FromBenjamin Kaplan <benjamin.kaplan@case.edu>
Date2013-08-24 21:03 -0700
SubjectRe: List getting extended when assigned to itself
Message-ID<mailman.207.1377403426.19984.python-list@python.org>
On Sat, Aug 24, 2013 at 8:52 PM, Krishnan Shankar
<i.am.songoku@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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web