-1

i have been working on this for 3 hours now but i have no clue how to do it

can anyone help me with this?

values = [1, 2, 3, 4, 5]

temp = values[0]

for index in range (len(values) -1):
    values[index] = values [index]

values[len(values)-1] = temp
print values

i want the printed values to be in order as [2,3,4,5,1] by simply changing those in the brackets

  • 2
    Lists have some useful methods: `values.append(values.pop(0))` – Ashwini Chaudhary May 29 '15 at 10:37
  • I solved it by myself thanx everyone tho! values = [1, 2, 3, 4, 5] temp = values[0] for index in range (len(values) -1): values[index] = values [index+1] values[len(values)-1] = temp print values – Lachlan O'Connor May 29 '15 at 10:44
  • possible duplicate of [Efficient way to shift a list in python](http://stackoverflow.com/questions/2150108/efficient-way-to-shift-a-list-in-python) – Vidhya G May 29 '15 at 10:55
  • more duplicates: http://stackoverflow.com/questions/9457832/python-list-rotation http://stackoverflow.com/questions/1212025/moving-values-but-preserving-order-in-a-python-list – Vidhya G May 29 '15 at 13:11

4 Answers4

3

deque is more efficient way to do

In [1]: import collections

In [3]: dq = collections.deque([1,2,3,4,5])

In [4]: dq.rotate(-1)

In [5]: dq
Out[5]: deque([2, 3, 4, 5, 1])
Ajay
  • 5,267
  • 2
  • 23
  • 30
1

What you are trying to achieve is not available in the python libraries but you can leverage slicing to rotate list

Implementation

def rotate(seq, n = 1, direc = 'l'):
    if direc.lower() == 'l':
        seq = seq[n:] + seq[0:n]
    else:
        seq = seq[-n:] + seq[:-n]
    return seq

Demonstration

>>> rotate(values)
[2, 3, 4, 5, 1]
>>> rotate(values,2,'l')
[3, 4, 5, 1, 2]
>>> rotate(values,2,'r')
[4, 5, 1, 2, 3]
Abhijit
  • 62,056
  • 18
  • 131
  • 204
0

Simple but powerful slice syntax:

values = [1, 2, 3, 4, 5]
shifted = values[1:]+values[:1]
assert shifted == [2, 3, 4, 5, 1]
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0

How about time one-liner, in the spirit of sleepsort:

while values != [2, 3, 4, 5, 1]: random.shuffle(values)
Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120