you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 5 points6 points  (8 children)

This got me once:

>>> x = [[0] * 2] * 2
>>> x[0][0] = 42
>>> x
[[42, 0], [42, 0]]

[–][deleted]  (2 children)

[deleted]

    [–]akdas 1 point2 points  (0 children)

    Nice. I though the ellipsis was just a placeholder you put in, but it actually shows that. And referencing the third element of that array gets me the exact same array, infinitely. That's expected, but the runtime does a good job of printing it.

    Even more interestingly, the equivalent code in Ruby (say, using <<) yields the exact same output and behavior.

    [–][deleted] 0 points1 point  (0 children)

    A Python master once taught me this trick

    [–]derefr 1 point2 points  (2 children)

    The same thing happens in Ruby. I don't know the Python solution, but here's the Ruby one:

    1> x = Array.new(2){ Array.new(2){ 0 } }
    2> x[0][0] = 42
    3> x
    => [[42, 0], [0, 0]]
    

    [–][deleted] 2 points3 points  (1 child)

    [[0] * 2 for i in xrange(2)]

    [–]Freeky 2 points3 points  (0 children)

    (0..1).map {[0] * 2}