-1

here is the code I'm working with but it keeps moving the element backwards once not multiple times

def backwards(input_list):
    total = 0
    while total < 3:
        total +=1
        return input_list[1:] + input_list[:1]

example : a = from ['a', 'b', 'c', 'd'] to ['b', 'c', 'd', 'a'] but multiple times

3 Answers3

1

Your issue is that you return on the first iteration of the loop so it runs only once. you can fix it like this:

def backwards(input_list):
    total = 0
    while total < 3:
        total +=1
        input_list = input_list[1:] + input_list[:1]
    return input_list

but we can improve that:

def backwards(input_list):
    total = 0
    while total < 3:
        total +=1
        input_list.append(input_list.pop(0))
    return input_list
Nullman
  • 4,179
  • 2
  • 14
  • 30
0

You can use np.roll() for this. For example:

np.roll(['a', 'b', 'c', 'd'], -1).tolist()

will return:

['b', 'c', 'd', 'a']
Alp Aribal
  • 370
  • 1
  • 11
-1

I'm not 100% sure what you're trying to achieve, but you might like:

a[::-1]

Which would return your list, but "backwards" using slicing:

['d', 'c', 'b', 'a']
Thomas Kimber
  • 10,601
  • 3
  • 25
  • 42
  • If you don't understand the question - don't answer! Comment and ask for clarifications instead. Anyway, this is not at all related to the question. OP is trying to make a cyclic shift of the list, not reverse it – Tomerikoo Feb 04 '21 at 12:44