Re: Changing a Value in List of lists

Discussion in 'Python' started by Chris Angelico, Sep 2, 2012.

  1. On Sun, Sep 2, 2012 at 7:44 PM, Rishabh Dixit <> 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
    Chris Angelico, Sep 2, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==

    List of lists of lists of lists...

    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==, May 8, 2006, in forum: Python
    Replies:
    5
    Views:
    403
    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==
    May 15, 2006
  2. yomgui

    list of lists of lists ....

    yomgui, Jul 28, 2006, in forum: Python
    Replies:
    6
    Views:
    311
    yomgui
    Jul 31, 2006
  3. Lynn
    Replies:
    5
    Views:
    143
    Anno Siegel
    Sep 12, 2005
  4. Mark Lawrence

    Re: Changing a Value in List of lists

    Mark Lawrence, Sep 2, 2012, in forum: Python
    Replies:
    0
    Views:
    224
    Mark Lawrence
    Sep 2, 2012
  5. Terry Reedy

    Re: Changing a Value in List of lists

    Terry Reedy, Sep 2, 2012, in forum: Python
    Replies:
    2
    Views:
    191
    Rishabh Dixit
    Sep 3, 2012
Loading...

Share This Page