Hướng dẫn python shift array

I am trying to shift the elements of an array cyclically so all elements are replaced with the previous element, and the last rotates to the first poaition, like so: shift(1, [5, 6, 7])=>[7, 5, 6].

The following code only returns [7,5]. Could someone please tell me what is causing this to happen? I went through the code step by step and simply could not find a solution. I also tried 3 different interpreters.

def shift(key, array):
    counter = range(len(array)-1)
    new = counter
    for i in counter:
        new[i] = array[i-key]
    return new

print shift(1, [5, 6, 7])

Hướng dẫn python shift array

asked Apr 8, 2013 at 3:37

1

range(5) returns [0, 1, 2, 3, 4]. It excludes 5.

Just remove the -1 from range(len(array)-1) and it should work.

You could also use list slicing:

def shift(key, array):
    return array[-key:] + array[:-key]

answered Apr 8, 2013 at 3:41

BlenderBlender

279k51 gold badges423 silver badges487 bronze badges

Here is the python way:

def shift(key, array):
    return array[-key:]+array[:-key]

Hướng dẫn python shift array

Loïc

11.4k1 gold badge28 silver badges47 bronze badges

answered Apr 8, 2013 at 3:46

Petar IvanovPetar Ivanov

89.4k10 gold badges79 silver badges94 bronze badges

You need to remove the -1 from your range:

counter = range(len(array))

If you want a faster method though, You could instead try using a deque?

from collections import deque

def shift(key, array):
    a = deque(array) # turn list into deque
    a.rotate(key)    # rotate deque by key
    return list(a)   # turn deque back into a list


print (shift(1, [5, 6, 7]))

answered Apr 8, 2013 at 3:44

Hướng dẫn python shift array

SerdalisSerdalis

9,9772 gold badges36 silver badges57 bronze badges

1

The answers are good, but it doesn't work if the key is greater than the length of the array. If you think the key will be larger than the array length, use the following:

def shift(key, array):
    return array[key % len(array):] + array[:key % len(array)]

A positive key will shift left and a negative key will shift right.

answered Apr 8, 2013 at 4:22

The numpy package contains the roll function to perform exactly this task:

import numpy as np
b=[5,6,7]
c=np.roll(b,1).tolist()

>>> c
[7, 5, 6]

A function using this and returning a list is:

def shift(array,key):
    return np.roll(array,key).tolist()

answered Jun 16, 2016 at 13:40

Hướng dẫn python shift array

Adrian TompkinsAdrian Tompkins

6,2033 gold badges33 silver badges77 bronze badges

#!/usr/bin/env python

def ashift(key,array):
        newqueue = array[-key:]
        newqueue.extend( array[:-key] )
        return newqueue


print ashift( 1, [5,6,7] )
print ashift( 2, [5,6,7] )

Results in:

$ ./shift 
[7, 5, 6]
[6, 7, 5]

The only potential penalty is if the array is sufficiently large, you may encounter memory issues, as this operation is doing a copy. Using a "key" with an absolute value greater than the length of the array will result in wrapping and results may not be as expected, but will not error out.

answered Apr 8, 2013 at 4:43

Hướng dẫn python shift array

Good old fashioned POP & APPEND

arr = [5, 6, 7]

for _ in range(0, 2):
    shift = arr.pop(0)
    arr.append(shift)

print(arr)

=>[7, 5, 6]

answered Feb 16, 2019 at 14:51

EdsterEdster

1032 silver badges8 bronze badges

You can use numpy roll

>>> x = np.arange(10)
>>> np.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> np.roll(x, -2)
array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

answered Jun 2, 2021 at 19:25

HugoHugo

1,3561 gold badge9 silver badges8 bronze badges

Not the answer you're looking for? Browse other questions tagged python arrays or ask your own question.