We have already seen in a previous article how to rotate lists with slicing in Pyhton. In this case we are going to see an alternative to be able to rotate lists with Collections in Python. Although managing slicing is simple, perhaps using the Collections library is even simpler…
But we go by steps. The first thing will be to create the list. In this case we are going to create a simple list of numbers:
list = [1,2,3,4,5,6,7,8,9]
To be able to use the objects from the Collections library of Python what we will have to do is import the library. So at the beginning of our program what we will do is import it. Although we are only going to import the deque object. So we will use the from...import statement to do it as follows:
from collections import deque
The deque object is a queue that allows us to add elements to both the beginning and the end of the queue. The first thing we will do is convert the list we have into a deque object of type queue.
list = deque(list)
Now, to be able to rotate the list we are going to rely on the .rotate() method. To this method we will pass as a parameter the number of elements that we want to rotate to the right. In this way, if we want to rotate three elements we will write the following:
list.rotate(3) print (list(list))
In this way the initial list would look like this:
[7, 8, 9, 1, 2, 3, 4, 5, 6]
In it we see that we have moved three positions to the right and therefore the beginning of the list has begun to be filled with the elements that overflowed the list.
We see that in order to print the list in Python we have relied on the
list()function, which converts the queue into a list so that it can be printed on the screen.
But the .rotate() method also allows the parameter to be negative. In this case the behavior of the .rotate() method will be to rotate the elements to the left. In this way we could write the following code:
list.rotate(-6) print (list(list))
In this case we have rotated 6 elements to the left, leaving us with the following result of the list:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
We must keep in mind that we had already rotated 3 elements to the right in the initial list, so the final result of moving 6 elements to the left would be the same if we had rotated 3 elements to the left in the initial list. In the rotation to the left we see that the elements that overflow to the left are added to the end of the list.
In this simple way we have managed to rotate lists with Collections in Python by using the deque object and its .rotate() method.
