0

I'm learning python, and am trying to move values in a list in loop. But dont know how to do it. So, if I have this:

list1 = ['a', 'b', 'c', 'd']

How can i rotate the values to right by one and get ['d', 'a', 'b', 'c'] and then move again [ 'c', 'd', 'a', 'b']?

FirstTimer12
  • 97
  • 2
  • 4

2 Answers2

1

Just use list slice notation:

>>> list1 = ['a', 'b', 'c', 'd']
>>> list1[:-1]
['a', 'b', 'c']
>>> list1[-1:]
['d']
>>> list1[-1:] + list1[:-1]
['d', 'a', 'b', 'c']
>>> def rotate(lst):
...   return lst[-1:] + lst[:-1]
... 
>>> list1
['a', 'b', 'c', 'd']
>>> list1 = rotate(list1)
>>> list1
['d', 'a', 'b', 'c']
>>> list1 = rotate(list1)
>>> list1
['c', 'd', 'a', 'b']
Daniel Martin
  • 23,083
  • 6
  • 50
  • 70
0

The easiest why would be to use deque.

from collections import deque

d = deque(list1)
d.rotate(1)
print(d)
d.rotate(1)
print(d)

Gives:

deque(['d', 'a', 'b', 'c'])
deque(['c', 'd', 'a', 'b'])
Marcin
  • 215,873
  • 14
  • 235
  • 294