简体   繁体   中英

How to move an element in a Python list to another position in the list (not the end)

I have a string "cab" I want my program to return "abc"

Because Python strings are immutable, I converted this to a list but I can only seem to move the first element over to the end of the list in Python. How can I designate where I want to move this element in the list?

If you just need to swap the position of two items in a list, you can do so using tuple assignment.

s = ['c','a','b']
s[0],s[1] = s[1],s[0]
print(''.join(s))
# prints:
acb

If you have a longer list, and you want to move an element to a specific location, you can use pop and insert .

To move the 'w' at index 5, forward to index 2, you can do:

s = list('helloworld')

s.insert(2, s.pop(5))

print(''.join(s))
# prints:
hewlloorld

To move the 'e' at index 1, backwards to index 7, you would use:

s = list('helloworld')

s.insert(7, s.pop(1)) 

print(''.join(s))
# prints:
hlloworeld

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM