mercredi 1 septembre 2021

Why does assigning a value to one element change the value of all (python) [duplicate]

all i want to do is assign the first element in this 50x2 2d array of zeros a random value. But as you can see instead of just changing the first element (aka the first element of the first pair), it changes the first element of every pair. Why is that and how do I stop it. I'm new to python so I'm probably missing something obvious.

import random
import time

points = [[0]*2]*50
print(points)

random.seed(time.time())
        
points[0][0] = random.random()
print(points)

output:

[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 0], [0, 0]]
[[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0],[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557,0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0], [0.5832599097950557, 0],
[0.5832599097950557, 0], [0.5832599097950557, 0]]



Aucun commentaire:

Enregistrer un commentaire