9
Awlex
4y

Fuck me sideways, it took me so long to figure out what caused a certain bug. Thanks python
>>> list = [[0] * 2] * 2
>>> list
[[0, 0], [0, 0]]
>>> list[0][0] = 1
>>> list
[[1, 0], [1, 0]]

Comments
  • 3
    I mean, []*2 copies the indices, hence the references in the case of arrays. Indices must be of finite length, so arrays probably don't contain other arrays.
  • 1
    References!
  • 0
    Damn I didn't know that.
  • 0
    Makes sense though
  • 0
    This is a nice example of why basic collections like arrays should be value types.
    In most languages they are reference types and it sucks.
  • 1
    @Lensflare In all languages that guarantee tolerable speed and memory safety, all variables are fixed length. Eg. in C/C++ you can have an int[20] as a value type, but you definitely can't have an int[], because it doesn't have a size and hence can't be allocated. So if you want to pass around int[]-s, as you probably do, you'll have to use a pointer, which is of fixed size.

    In python it isn't a pointer but rather some structure, but that structure still can't store the value of the array, only a reference to it, as it still needs to be of fixed size.
  • 1
    Also, strings are often made immutable through an abstraction layer, but they're still reference types. You shouldn't copy arbitrary arrays when passed or stored because arrays can get very large.
  • 1
    @Lor-inc in order to optimize for speed, value type collections are implemented with copy-on-write semantics. And with value types, the question of mutability is not about the type but about the declaration of the value.
    Together, you get nearly perfect speed, safety and convenience.
  • 0
    And in the rare cases when you really need to pass a collection by reference, all languages have some kind of syntax for that.
    But it doesn't go the other way. You just can't pass a reference type collection by value. You'll need to write some custom copy code.
Add Comment