-3

I'm trying to make integers containing within value to shift from leftmost to rightmost. For example if values is [1,2,3,4,5] after running the code it would be [2,3,4,5,1].

I managed to write the code but I some how made the value shift from rightmost to leftmost which is other way around. Like [5,1,2,3,4]. Been sitting for hours trying to figure it out, any hands? Thank you

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

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

print values
heemayl
  • 39,294
  • 7
  • 70
  • 76
lufee
  • 169
  • 2
  • 10
  • 1
    Are you sure you're not lying and that code is actually from [**here**](http://www.acdict.edu.au/documents/NoviceProgrammersCorney.pdf)? – Stefan Pochmann May 31 '16 at 01:59
  • @StefanPochmann, that code is quite common for this sort of problem. – RoadRunner May 31 '16 at 04:13
  • @RoadRunner Well, I had googled the `for index...` line and Google found exactly one hit, the one I showed. And it's byte-for-byte the exact same four lines. But the original and main reason I call BS is that there's no way they wrote the above version and *"for hours"* unsuccessfully tried to write the other direction, as that works exactly the same (and actually is slightly simpler, as `range` upwards is nicer). – Stefan Pochmann May 31 '16 at 12:39
  • Yeah that's true. I said that it's quite common because I have pretty much the same code in my database. Oh well. I hope he figured it out I guess. It's just the way you commented, I found it hilarious. – RoadRunner May 31 '16 at 13:08

3 Answers3

2

In your case, knowing the length of the list is not necessary.

You can just use list slicing:

values[1:] + values[:1]

Example:

In [8]: values = [1,2,3,4,5]

In [9]: values[1:] + values[:1]
Out[9]: [2, 3, 4, 5, 1]
heemayl
  • 39,294
  • 7
  • 70
  • 76
2

This kind of rotation is most easily implemented using slice concatenation:

def rotate(lst, n):
    n = n % len(lst)  # allows rotations beyond length
    return lst[n:] + lst[:n]

> rotate([1,2,3,4,5], 1)  # rotate forward
[2, 3, 4, 5, 1]

> rotate([1,2,3,4,5], -2)  # rotate backward
[4, 5, 1, 2, 3]

Repairing your original code, however:

temp = values[0]  # store the first value cause it'll be overwritten in loop
for index in range(len(values) - 1):
    values[index] = values[index + 1]  # shift values to the left
values[len(values) - 1] = temp  # write former first to last
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

You could cycle through the list using mutability, like this:

    def cycle(input_list):
        list_copy = input_list[:]
        list_copy.append(list_copy.pop(0))
        return list_copy

    # Output
    >>> input_ist = [i for i in range(1, 6)]   # Same as [1,2,3,4,5]
    >>> cycle(input_list)
    [2, 3, 4, 5, 1]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75