I have a variable that I increment (just say?), And then add to the array. I do it several times in a loop.

I came to python from C and got used to the fact that if I don’t say that I pass an element by reference, I don’t pass it by reference. Now, in python, all the elements of my list are always the same and correspond to this variable.

In the documentation I was digging, I admit that it is bad, the answer should not be deep, but it will be cool if someone answers faster than I get to the bottom.

Part of the code:

array = [] for i in range(3): array.append(Pose) Pose.pos.x += (width * 0.001) 

At the output, I get an array consisting of 3 identical elements

ZY "Pose" is so necessary, it is not me who is not literate.

  • one
    These are not three identical elements, they are the same element added three times. - Igor
  • @Igor, yes, I understand. But I add an item, then change and add again. And I expect that the first element will not change with this. Lists not only from manually added elements are created? I don’t need to do 9469628823 spare variables, I don’t know in advance the size of the array. - Mikhail Kraev Nov.

2 answers 2

Mikhail, if you write three different lines on a piece of paper, it will not turn into three sheets of paper, it will be the same one sheet of paper.

To work with three different objects, you need to somehow create three different objects.

How to do it depends on what your Pose .

In python, the name of the class is written with a capital letter, which is somewhat discouraging, because the actions you are trying to do with Pose are not very meaningful for the class.

Perhaps you need to first instantiate individual instances of the class, and work with them already:

 array = [] for i in range(3): p = Pose() array.append(p) p.pos.x += (width * 0.001) 

If you have a Pose contrary to the capital letter, and so is already an instantiated class instance, then you need to somehow copy it, or instantiate two more separate instances. To say exactly how best to do this, I need to see the definition of a class of which Pose is an instance. If you bring him, I can better help you.

     for i in range(3): p = Transform() // ссылка на новый объект array.append(p) p.pos.x = i * (width * 0.001) 
    • Well, great, that's just my Pose, so the Transform () class variable. And it still does not work. - Mikhail Kraev Nov.
    • @ MikhailKrayev between your code and the code in response is a huge difference. In response, each time a new element is added - andy.37 Nov.
    • It is possible, by the way array.append(Transform()); array[-1].pos.x = ... array.append(Transform()); array[-1].pos.x = ... - andy.37 10:46
    • The answer is poor quality. Please describe in words what is happening in your code. - mymedia