Asim Zaidi
Asim Zaidi

Reputation: 1

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?

Upvotes: 0

Views: 3809

Answers (1)

James
James

Reputation: 36608

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

Upvotes: 2

Related Questions