+ 6

Paranormal activity in Python: Why don't these two codes give the same result?

I'm getting totally mad. Code 1: an = [] anadir3 = [1,2,1,2,1,2] for i in range(3): an += [anadir3] for i in range(3): an[i][2*i+1]+=1 print(an) ------------------------------- Code 2: an = [] an = [[1,2,1,2,1,2],[1,2,1,2,1,2],[1,2,1,2,1,2]] for i in range(3): an[i][2*i+1]+=1 print(an)

17th Feb 2018, 2:20 AM
Pablo Lizcano Sánchez-Cruzado
6 odpowiedzi
+ 12
When you add anadir3 to an in your first code, you not only assign the contents of anadir3 to an. You assign anadir itself to an. Hence, by altering an, you directly alter anadir3. In this case, an contains three copies of anadir3, and altering any copy of the three will directly alter the other remaining copies.
17th Feb 2018, 2:27 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Yep, python
17th Feb 2018, 2:21 AM
Pablo Lizcano Sánchez-Cruzado
+ 1
How can I assign just the content, preserving its value?
17th Feb 2018, 2:29 AM
Pablo Lizcano Sánchez-Cruzado
0
question is this python?
17th Feb 2018, 2:19 AM
Emperor Bob
Emperor Bob - avatar
0
sorry then i cant help you
17th Feb 2018, 2:21 AM
Emperor Bob
Emperor Bob - avatar