multiple index inconsistency
Mark McEahern
marklists at mceahern.com
Wed Sep 18 17:17:38 EDT 2002
[bert]
> The following line of code
> >>> a = 3*[range(3)]
> produces
> [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
>
> If I then write, say,
> >>> a[0][1] = 3.7
> I get
> [[0, 3.7, 2], [0, 3.7, 2], [0, 3.7, 2]]
> and not
> [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]]
>
> Now if I write
> >>> a = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
> instead, and then
> >>> a[0][1] = 3.7
> I get the result I expected (and wanted):
> [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]]
> Why the inconsistency? Is this a bug or am I missing something?
Short answer: lists are mutable. ints aren't.
So when you do this:
a = 3 * [range(3)]
you're basically doing this:
l = range(3)
a = 3 * [l]
The result is effectively:
[[l], [l], [l]]
when you modify one of the lists, "all of them" are affected.
A better approach:
x = 3
y = 3
a = [range(x) for x in range(y)]
(I assume x and y are different in theory.)
Now, try this:
for x in a:
print id(x)
and compare that to the list generated by 'a = 3 * [range(3)]'
Cheers,
// mark
-
More information about the Python-list
mailing list