Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Changing a Value in List of lists

Reply
Thread Tools

Re: Changing a Value in List of lists

 
 
Chris Angelico
Guest
Posts: n/a
 
      09-02-2012
On Sun, Sep 2, 2012 at 7:44 PM, Rishabh Dixit <(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Changing a Value in List of lists Terry Reedy Python 2 09-03-2012 05:05 AM
Re: Changing a Value in List of lists Mark Lawrence Python 0 09-02-2012 11:17 AM
list of lists of lists .... yomgui Python 6 07-31-2006 07:28 PM
List of lists of lists of lists... =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?= Python 5 05-15-2006 11:47 AM
converting a hash where the value is a list of lists to just a list Lynn Perl Misc 5 09-12-2005 01:34 PM



Advertisments