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.
asked Apr 8, 2013 at 3:37
1
Just remove the You could also use list slicing:
answered Apr 8, 2013 at 3:41
BlenderBlender 279k51 gold badges423 silver badges487 bronze badges Here is the python way:
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
If you want a faster method though, You could instead try using a deque?
answered Apr 8, 2013 at 3:44
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:
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:
A function using this and returning a list is:
answered Jun 16, 2016 at 13:40
Adrian TompkinsAdrian Tompkins 6,2033 gold badges33 silver badges77 bronze badges
Results in:
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
Good old fashioned POP & APPEND
answered Feb 16, 2019 at 14:51
EdsterEdster 1032 silver badges8 bronze badges You can use numpy roll
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. |