Irt Irt - 1 year ago 82
Python Question

Adding elements to list in python in proper order

I want to add element to list using specific index. Using insert it is not working for me as it should in all cases. Please take a look:

rest = [666, 555, 222]
s= sorted(rest)

list1 = []

print list1

So what I wanted to achieve - highest value mapped to lowest from rest list.
But what I get is:
1, 3, 2 and the goal is to be 1, 2, 3 (in this case).

I understand that that is how insert function works, but is there any other way to acheive what I want?

Answer Source

Is it what you are looking for?

rest = [666, 555, 222]
s= sorted(rest)

list1 = [0] * len(rest)    
list1[rest.index(s[0])] = 3
list1[rest.index(s[1])] = 2
list1[rest.index(s[2])] = 1

print list1

The above code gives [1, 2, 3] as output (as you expect).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download