Imagine I need to populate one list with objects of some class and the set objects' fields. For example I can do it this way (not the best way, according to best practices, but for me more interesting is how it works behind the scene):
import random
class Point:
coordinates = [0, 0]
ex = []
for i in range(0, 10):
ex.append(Point())
ex[i].coordinates[0] = random.randint(0, 25)
ex[i].coordinates[1] = random.randint(0, 25)
for i in ex:
print(i.coordinates)
print(id(i.coordinates))
After this I end up with situation when all Points in ex
list contains the same coordinates
object (same id). But if I change assigning each list element to assigning list itself:
ex[i].coordinates = [random.randint(0, 25), random.randint(0, 25)]
It works as expected.
Could one point me out how it works under the hood and what's the difference between these 2 approaches?