c1234
c1234

Reputation: 13

Shifting elements forward in a list

I am trying to do the following; [1,2,3,4] -> [1,1,2,3]

Here is my attempt, but not working. I want to modify this in place.

A = [1,2,3,4]
temp = A[0]
for i in range(1, len(A)-2):
    A[i] = temp
    temp = A[i]

But instead I am getting back [1,1,3,4]. I want to do backward as well, but so far I can't shift by one forward.

Upvotes: 1

Views: 250

Answers (1)

cs95
cs95

Reputation: 402814

Unless I'm missing something, perhaps some simple list slicing and assignment is all you need?

A[1:] = A[:-1]
A
# [1, 1, 2, 3]

Similarly, shifting backward by 1 would be

A[:-1] = A[1:]

In general, to shift by N, use:

A[n:] = A[:-n]

Shifting forward by 1 can also be done with a for loop and a temp variable:

temp = A[0]
for i in range(len(A)-1):
    temp, A[i+1] = A[i+1], temp

A
# [1, 1, 2, 3]

Upvotes: 5

Related Questions