0
def list_move_back(new_value, value_list):
    for i in reversed(value_list):
        if value_list.index(i) != len(value_list)-1:
            value_list[value_list.index(i)+1] = i
    value_list[0] = new_value
    return value_list

I want to get the following result:

list_example = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_example = list_move_back(12, list_example]
print(list_example)
>>>[12, 1, 2, 3, 4, 5, 6, 7, 8, 9]

It works if I run the function two times:

list_example = list_move_back(12, list_example]
    print(list_example)
    >>>[12, 12, 1, 2, 3, 4, 5, 6, 7, 8]

but if I want to run it a third time, the result looks like that:

list_example = list_move_back(12, list_example]
        print(list_example)
        >>>[12, 12, 1, 1, 3, 4, 5, 6, 7, 8]

The first 1 should be a 12. I have no idea why it doesn't work.

chevybow
  • 9,959
  • 6
  • 24
  • 39

2 Answers2

4

Just use list slicing:

def list_move_back(new_value, list_of_values):
    return [new_value] + list_of_values[:-1]

Explanation: list_of_values[:-1] returns all the elements except for the last. By appending it to the new value, you get the wanted result. This answer has a pretty cool explanation of how list slicing works.

Also, if for some reason you'd like the "verbose" way to do this (maybe for an exercise or whatever), here's a way to go about it:

def list_move_back(new_value, list_of_values):

    for i in range(len(list_of_values)-1, 0, -1):
        list_of_values[i] = list_of_values[i-1]
    list_of_values[0] = new_value

    return list_of_values

I'd recommend list slicing over this method 9/10 times but again, I'm just leaving this here because there might be a case where someone wants to do this as some sort of mental exercise for indexing.

Saucy Goat
  • 1,587
  • 1
  • 11
  • 32
1

If you need the list to change in place, you can use the list methods .pop() to remove the last item and .insert(0,value) to add an item to the front:

>>> L = list(range(1,11))
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> id(L)
1772071032392
>>> L.pop();L.insert(0,12)
10
>>> L
[12, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> id(L)  # same list id, modified in place...
1772071032392
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • 1
    Hey there! My answer has been accepted but I'd like to refer to yours as well. I'm quite the noobie here at SO so I'm unsure as to what would be the best practice. Should I add your answer to mine or maybe just refer it? – Saucy Goat Dec 13 '19 at 17:58
  • 1
    @SaucyGoat No need to do anything. If you like the answer upvote :^) – Mark Tolonen Dec 13 '19 at 18:02
  • 1
    Got it! Was just asking because sometimes the author of the accepted answer adds content from other answers. Cheers :) – Saucy Goat Dec 13 '19 at 18:03