Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shift values to right and filling with zero

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading