Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Changing a Value in List of lists (http://www.velocityreviews.com/forums/t951707-re-changing-a-value-in-list-of-lists.html)

Chris Angelico 09-02-2012 09:57 AM

Re: Changing a Value in List of lists
 
On Sun, Sep 2, 2012 at 7:44 PM, Rishabh Dixit <rishabhdixit11@gmail.com> wrote:
>
> Hi all,
>
> I have a doubt regarding how the list work in following case-
>
>>>> ls=[[0]*5]*5
>>>> ls[1][1]+=1
>>>> ls

> [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1,
> 0, 0, 0]]
>
>
> Here, according to me only one value in ls should be incremented but it is
> increasing 1 value in all the lists of ls. Why??


When you take the list [[0,0,0,0,0]] and multiply it by 5, you get a
list with five references to the same inner list. That's where the
confusion is coming from. Then when you change one of them, it changes
all five displayed versions, since they're all still the same list.

ChrisA


All times are GMT. The time now is 11:16 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.