# Python: list is populating with wrong order?

I have chain of 3 bones which are influenced by IK constraint. IK is added to bone named IK B#3:
I'm trying to populate them into array in reverse order, i.e. IK B#1, IK B#2, IK B#3 in that order.
Code snipet:

bone_list = []

def populate_array(self):

index = self.ik.chain_count - 1
currentBone = activeBone
for i in range(-1, self.ik.chain_count - 1):
print("\nindex is :"+str(index)+"\n\tcurrent bone is: "+str(currentBone.name))
self.bone_list.insert(index, currentBone)
index -= 1
currentBone = currentBone.parent

#print out array
for b in self.bone_list:
print(b.name)


When i execute this code i'm getting this result:

Why array is populated in that order, what is wrong with my code?

• You should "append" to bone_list instead of "insert" – lemon Apr 24 '18 at 12:38
• Uh, thanks! Write it as an answer so i could accept it. – blablaalb Apr 24 '18 at 12:45
• and can you explain, what has been happening with my version.Why elements was inserted with that order? I don't get it. – blablaalb Apr 24 '18 at 12:50
• I'm voting to close this question as off-topic because this is a general Python problem, not specific to blender, which will be more suited to one of the programming Stack Exchange sites. – Ray Mairlot Apr 24 '18 at 15:47
• Since my question was related to blender scripting i decided to ask it here. Sorry if did something wrong. – blablaalb Apr 25 '18 at 11:32

The question is not a Blender question, but anyway...

So use append(currentBone) instead of insert(index, currentBone), to have [IKB3, IKB2, IKB1].

Or use insert(0, currentBone) instead of insert(index, currentBone) to have [IKB1, IKB2, IKB3].

But concerning "why" your usage of insert does not work:

# Step1:

bone_list is empty and index is 2.

So bone_list.insert(2, IKB3) gives bone_list = [IKB3]. Explanation: Python tolerates that even if there is no element at position 2.

And index becomes 1.

# Step2:

bone_list.insert(1, IKB2) gives bone_list = [IKB3, IKB2]. Explanation: still no element at position 1 (IKB3 is at position 0), so IKB2 is added at the end (which is the closest position to '1').

And index becomes 0.

# Step3:

bone_list.insert(0, IKB1) gives bone_list = [IKB1, IKB3, IKB2]. Explanation: there is now an element at 0, so as expected Python add IKB1 before it.