A simple question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tuvas

    #1

    A simple question

    I know the answer is probably really simple to this, and I feel bad to
    even ask, but I can't find the answer anywhere... Let me show what
    happened, then ask the question.
    [color=blue][color=green][color=darkred]
    >>> x=[[0]*2]*2
    >>> x[/color][/color][/color]
    [[0, 0], [0, 0]][color=blue][color=green][color=darkred]
    >>> x[0][1]=1
    >>> x[/color][/color][/color]
    [[0, 1], [0, 1]][color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    The question now. Why is the output list [[0, 1], [0, 1]] and not [[0,
    1], [0, 0]]? And how can I make it work right? I do know that x[0][1]
    will always give the value of that specific coordinate, but never
    before have I tried to manipulate rows like this, and I'm finding I
    need to. Thanks!

  • skip@pobox.com

    #2
    Re: A simple question

    [color=blue][color=green][color=darkred]
    >>> x=[[0]*2]*2[/color][/color][/color]

    This replicates the references. It doesn't copy objects.

    This short transcript demonstrates that concept:
    [color=blue][color=green][color=darkred]
    >>> x = [[0, 0], [0, 0]]
    >>> map(id, x)[/color][/color][/color]
    [16988720, 16988160][color=blue][color=green][color=darkred]
    >>> y = [[0]*2]*2
    >>> y[/color][/color][/color]
    [[0, 0], [0, 0]][color=blue][color=green][color=darkred]
    >>> map(id, y)[/color][/color][/color]
    [16988520, 16988520]

    The object x refers to is a list with references to two other lists. The
    object y refers to is a list with two references to the same list.

    Skip

    Comment

    • nnorwitz@gmail.com

      #3
      Re: A simple question

      Skip answered why, but not how to make it work right:
      [color=blue][color=green][color=darkred]
      >>> x = [[0]*2 for x in range(2)]
      >>> x[/color][/color][/color]
      [[0, 0], [0, 0]][color=blue][color=green][color=darkred]
      >>> x[0][1]=1
      >>> x[/color][/color][/color]
      [[0, 1], [0, 0]]

      Cheers,
      n

      Comment

      • Ben Cartwright

        #4
        Re: A simple question

        Tuvas wrote:[color=blue]
        > Why is the output list [[0, 1], [0, 1]] and not [[0,
        > 1], [0, 0]]? And how can I make it work right?[/color]



        --Ben

        Comment

        • Tuvas

          #5
          Re: A simple question

          Ahh, that make sense! Thanks a ton!

          Comment

          Working...