Home > Blockchain >  How can I change Index of an object in a list without deleting and re-adding the item in python
How can I change Index of an object in a list without deleting and re-adding the item in python

Time:07-13

I have a list of class objects in a list . I want to change index of -1 element to 0 . I want rest of the objects to shift their index automatically . I cannot delete the item and re-add it into list using Insert() . What can I do ? I want to keep the list intact as it is but just need to change index of some elements within list

here is an example

list -----> [1,2,3,4,5,6,7,8,9,0]

what I want to do is change 0 to 0th index from -1 index value

result required ----> [0,1,2,3,4,5,6,7,8,9]

Please note that I have a list of class objects in a kivy(module) class . I cannot delete and re - add the same widget . I want to change the Index

CodePudding user response:

Try this:

l = [1,2,3,4,5,6,7,0]
print(f'original : {l}')

## dynamically generate "order"
order = [n for n in range(len(l))]
order.insert(0, order[-1])
del order[-1]
print(f'order    : {order}')

## rearrange the list with generated "order"
l = [l[i] for i in order]
print(f'final    : {l}')

Output:

original : [1, 2, 3, 4, 5, 6, 7, 0]
order    : [7, 0, 1, 2, 3, 4, 5, 6]
final    : [0, 1, 2, 3, 4, 5, 6, 7]
  • Related