I have a list and I want the values to be shifted to right by 1 position and fill the index 0 with a value of 0.
For eg:
a = [8,9,10,11]
output = [0,8,9,10]
I tried the following:
a.insert(0,a.pop())
And the above line of code shifted to right and put the last element back at first.
a = [11,8,9,10]
Is there a way to do this?
Thanks
>Solution :
Use:
a = [8, 9, 10, 11]
a.pop()
a.insert(0, 0)
print(a)
Output
[0, 8, 9, 10]
Just insert 0 at index 0.
A note on performance
If you are planning on performing this operation multiple times, I suggest you use a deque so insert (appendleft in deque) and pop is O(1) instead of O(n):
from collections import deque
a = [8, 9, 10, 11]
d = deque(a)
d.pop()
d.appendleft(0)
print(d)
Output
deque([0, 8, 9, 10]) # list(d) if needed
See more on the time complexities of the operations here.