4 ms·
I've encountered a similar bug before. >>> arrays = [[]] * 5 >>> print arrays ... [[], [], [], [], []] >>> arrays[0].append(1) >>> print arrays ...
by kevinwuhoo 13y ago
I've encountered a similar bug before.
>>> arrays = [[]] * 5
>>> print arrays
... [[], [], [], [], []]
>>> arrays[0].append(1)
>>> print arrays
... [[1], [1], [1], [1], [1]]
- icebraining 13y agoThat's not a bug, it's just the result of Python variables being references to values, instead of actual values. When you write "[[]]", what you're doing is creating a list that holds a reference to another list. If you use a variable it's easier to understand: a = [] arrays = [a] * 5 What you have now is [a, a, a, a, a], so if you modify one of the lists, it's no wonder they all get modified: they're references to the same list.
- socillion 13y agoThat's because of the implicit copy() only copying by value 1 level deep? On the topic of the bug in OP, would a Python newbie expect the similarly confusing behavior caused by interactions between (im)mutability and function arguments being passed as a "reference"? Using OP's foo(): >>> a = [1,2,3] >>> foo(a) [1, 2, 3, 9] >>> a [1, 2, 3, 9] if 'a' were an immutable object like an int, it wouldn't be modified. >>> def bar(n): n += 1 print(n) >>> b = 3 >>> bar(b) 4 >>> b 3