Last updated: Apr 11, 2024
Reading timeยท6 min
append()
and pop()
numpy.roll
You can use list slicing to shift (rotate) a list in Python:
1
to the end.0
and going up to, but not
including index 1
.# โ Move the first list item to the back a_list = [1, 2, 3, 4, 5] new_list = a_list[1:] + a_list[:1] print(new_list) # ๐๏ธ [2, 3, 4, 5, 1]
The example moves the first list item to the back of the list.
If you need to move the last list item to the front of the list, use the following code sample instead.
# โ Move the last list item to the front a_list = [1, 2, 3, 4, 5] new_list = [a_list[-1]] + a_list[:-1] print(new_list) # ๐๏ธ [5, 1, 2, 3, 4]
The example uses list slicing to rotate the list.
The syntax for list slicing is a_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
start
index is omitted, it is considered to be 0
, if the stop
index is omitted, the slice goes to the end of the list.Python indexes are zero-based, so the first item in a list has an index of 0
,
and the last item has an index of -1
or len(a_list) - 1
.
The first slice a_list[1:]
starts at index 1
and goes to the end of the
list.
a_list = [1, 2, 3, 4, 5] new_list = a_list[1:] + a_list[:1] print(new_list) # ๐๏ธ [2, 3, 4, 5, 1]
The second slice a_list[:1]
starts at index 0
and goes up to, but not
including index 1
.
a_list = [1, 2, 3, 4, 5] print(a_list[1:]) # ๐๏ธ [1] print(a_list[:1]) # ๐๏ธ [2, 3, 4, 5, 1]
You can also create a reusable function that shifts (rotates) the list based on a supplied index.
def shift_list(lst, index=1): index = index % len(lst) return lst[index:] + lst[:index] a_list = [1, 2, 3, 4, 5] # ๐๏ธ [2, 3, 4, 5, 1] print(shift_list(a_list, 1)) # ๐๏ธ [2, 3, 4, 5, 1] (without passing index explicitly) print(shift_list(a_list)) # ๐๏ธ [3, 4, 5, 1, 2] print(shift_list(a_list, 2)) # ๐๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 3))
The shift_list
function takes a list and optionally an index as parameters and
rotates the list.
%
operator is there to account for a shift that is greater than the list's length.For example, 8 % 5 = 3
, so we only shift 3 times which is the same as shifting
8 times.
def shift_list(lst, index=1): index = index % len(lst) return lst[index:] + lst[:index] a_list = [1, 2, 3, 4, 5] # ๐๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 3)) # ๐๏ธ [4, 5, 1, 2, 3] print(shift_list(a_list, 8))
If an index is not provided, it defaults to 1
.
If an index of 1
is used, the first element in the list gets moved to the back
(becomes the last element).
Similarly, if an index of 2
is provided, the first two elements of the list
get moved to the back.
append()
and pop()
You can also use the
list.append() and
list.pop()
methods to rotate a list in Python.
# โ Move the first list item to the back a_list = [1, 2, 3, 4, 5] a_list.append(a_list.pop(0)) print(a_list) # ๐๏ธ [2, 3, 4, 5, 1]
The example moves the first list item to the back.
If you need to move the last list item to the front, use the following code sample instead.
# โ Move the last list item to the front a_list = [1, 2, 3, 4, 5] a_list.insert(0, a_list.pop()) print(a_list) # ๐๏ธ [5, 1, 2, 3, 4]
The list.pop()
method removes the item at the given position in the list and
returns it.
We used the method to remove and return the list item at position 0
.
The last step is to use the list.append()
method to move the removed list item
to the back of the list.
You can use the range class if you need to shift multiple items to the back of the list.
a_list = [1, 2, 3, 4, 5] for _ in range(2): a_list.append(a_list.pop(0)) print(a_list) # ๐๏ธ [3, 4, 5, 1, 2]
We used a range()
of 2 to shift the first 2 items of the list to the back.
print(list(range(2))) # ๐๏ธ [0, 1] print(list(range(3))) # ๐๏ธ [0, 1, 2]
The range
class is commonly used for looping a specific number of times in
for
loops.
You can also use the collections.deque class to shift (rotate) a list in Python.
from collections import deque deq = deque([1, 2, 3, 4]) deq.append(5) print(deq) # deque([1, 2, 3, 4, 5]) deq.rotate(1) print(deq) # deque([5, 1, 2, 3, 4]) deq.rotate(-1) print(deq) # deque([1, 2, 3, 4, 5]) deq.rotate(-1) print(deq) # deque([2, 3, 4, 5, 1])
The deque
class returns a deque
object that is initialized left-to-right with data from
the supplied iterable.
The
deque.rotate()
method rotates the deque n
steps to the right.
If n
is negative, the method rotates the deque
object to the left.
When the deque
is not empty:
deq.appendleft(deq.pop())
.deq.append(deq.popleft())
.Using the deque.rotate()
method is faster than using list slicing, in case you
need to optimize for performance.
numpy.roll
You can also use the numpy.roll() method to rotate a list.
First, make sure you have the numpy module installed.
Open your terminal in your project's root directory and run the following command.
pip install numpy # or pip3 pip3 install numpy
Now import and use the numpy.roll()
method as follows.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 1) print(new_array) # ๐๏ธ [5 1 2 3 4] new_array = np.roll(arr, -1) print(new_array) # ๐๏ธ [2 3 4 5 1] new_array = np.roll(arr, 2) print(new_array) # ๐๏ธ [4 5 1 2 3]
The numpy.roll
method rolls array elements along a given axis.
The first argument the method takes is the array.
The second argument is the number of places by which elements are shifted.
For example, if you pass 1
as the second argument to the method, the last
element gets shifted to the front.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 1) print(new_array) # ๐๏ธ [5 1 2 3 4]
If you pass 2
as the second argument, the last 2 elements get shifted to the
front.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, 2) print(new_array) # ๐๏ธ [4 5 1 2 3]
If you pass -1
as the second argument, the first element gets moved to the
back of the array.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, -1) print(new_array) # ๐๏ธ [2 3 4 5 1]
Similarly, if you pass -2
as the second argument, the first 2 elements get
moved to the back.
import numpy as np arr = np.array([1, 2, 3, 4, 5]) new_array = np.roll(arr, -2) print(new_array) # ๐๏ธ [3 4 5 1 2]
However, it is not necessary to load the entire numpy
library just to call the
np.roll()
method.
Using list slicing as shown in the first subheading should be sufficient for most use cases.
I've also written an article on how to move an item in a list in Python.
You can learn more about the related topics by checking out the following tutorials: