Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I change only a single element in a nested list in Python [duplicate]

I just met something really strange of Python:

>>> out=[[0]*3]*3
>>> out
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> out[0][1]
0
>>> out[0][1]=9
>>> out
[[0, 9, 0], [0, 9, 0], [0, 9, 0]]

well, obviously, what I want is :

[[0, 9, 0], [0, 0, 0], [0, 0, 0]]

isn't strange? I'm not very familiar with Python, but Python always impresses me with its intuitive behavior. But how it comes up with this?
... and how can I get what I need?

thanks!

Watt

like image 810
Matt Avatar asked Jun 07 '12 23:06

Matt


1 Answers

A strange behaviour indeed, but that's only because * operator makes shallow copies, in your case - shallow copies of [0, 0, 0] list. You can use the id() function to make sure that these internal lists are actually the same:

out=[[0]*3]*3
id(out[0])
>>> 140503648365240
id(out[1])
>>> 140503648365240
id(out[2])
>>> 140503648365240

Comprehensions can be used to create different lists as follows:

out = [ [0]*3 for _ in range(3) ]
like image 117
Zaur Nasibov Avatar answered Sep 19 '22 14:09

Zaur Nasibov