Predictive Hacks

How to Circular Shift Lists in Python

Let’s say that we have a Python List (or 1-D numpy array) and we want to shift it by n positions. Let’s see some ways of how we can do it.

Using pop

Assume that the list x is [1,2,3,4,5] let’s see how we can shift it by one position ahead.

x = [1,2,3,4,5]
x.append(x.pop(0))
x
[2, 3, 4, 5, 1]

Using Collection deque

This method allows us to shift by n elements ahead at once, using both directions, forward and backward. We just need to use the rotate method on the deque object. Note, that you can easily convert a deque object to a list like list(x) where x is a deque object.

import collections
x  = collections.deque([1, 2, 3, 4, 5])
x.rotate(1)
x
deque([5, 1, 2, 3, 4])

Note, that we also rotate it backwards by 2 steps:

x  = collections.deque([1, 2, 3, 4, 5])
x.rotate(-2)
x
deque([3, 4, 5, 1, 2])

Using numpy roll

Finally, we can use the roll method to the numpy arrays. It also supports both directions and n steps. For example:

import numpy
x=numpy.arange(1,6)
numpy.roll(x,1)
array([5, 1, 2, 3, 4])

Or, if we want to get 2 steps backwards:

x=numpy.arange(1,6)
numpy.roll(x,-2)
array([3, 4, 5, 1, 2])

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s