This is just a short part of my code (I'm new with python). The goal is to move all of the elements one position forward.
from turtle import Turtle
turtles = []
for i in range(4):
t = Turtle()
t.color("white")
t.setx(i*-20)
turtles.append(t)
for i in range(len(turtles)-1, 0, -1):
print(f"Element in position {i} with xcor {turtles[i].xcor()} will have the xcor {turtles[i-1].xcor()}")
turtles[i] = turtles[i-1]
turtles[0].forward(20)
print(" After modification of element in position 0")
print(f"Element in position 0 has xcor = {turtles[0].xcor()}")
print(f"Element in position 1 has xcor = {turtles[1].xcor()}")
However, I do not understand why the objects in positions 0 and 1 were modified at the same time.
Element in position 3 with xcor -60 will have the xcor -40
Element in position 2 with xcor -40 will have the xcor -20
Element in position 1 with xcor -20 will have the xcor 0
After modification of element in position 0
Element in position 0 has xcor = 20.0
Element in position 1 has xcor = 20.0
I was waiting to see the xcor = 0 for element in position 1.
CodePudding user response:
turtles[1]
and turtles[0]
are the same object. In other words, turtles[1] is turtles[0]
.
To copy a Turtle
, use .clone()
, for example, here:
turtles[i] = turtles[i-1].clone()