Home > Back-end >  Shift values to right and filling with zero
Shift values to right and filling with zero

Time:07-22

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

CodePudding user response:

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.

CodePudding user response:

Using np.roll.

import numpy as np
a = [8, 9, 10, 11]
a[-1] = 0
a = np.roll(a, 1)
# [0, 8, 9, 10]

CodePudding user response:

a.insert(0,a.pop())

This says to insert the value of a.pop() (the last element of the list) at index 0 in the array. So you shouldn't be surprised at the result. If you want to insert a 0, then you should specify it directly:

a.insert(0, 0)
  • Related