5

So I was attempting to write a very basic function that can move every element in the list one index earlier. And I think I am actually pretty close to the result I want.

For example if a list is

l = [1, 2, 4, 5, 'd']

I want it to be like that afterwards

l = [2, 4, 5, 'd', 1]

The reality of my code

l = [2, 4, 5, 1, 1]

Here is my code, I just don't know what is happening here after a lot of random attempts on changing the code...

Thank you guys in advance!

def cycle(input_list):
count = 0
while count < len(input_list):
     tmp = input_list[count - 1]
     input_list[count - 1] = input_list[count]
     count+=1
2Xchampion
  • 666
  • 2
  • 10
  • 24

4 Answers4

9

You could do this (in place):

l.append(l.pop(0))

In function form (makes a copy):

def cycle(l):
    ret = l[:]
    ret.append(ret.pop(0))
    return ret
jDo
  • 3,962
  • 1
  • 11
  • 30
2

As a python developer, I really cant resist typing this one liner

newlist = input[start:] + input[:start]

where start is the amount by which you have to rotate the list

Ex :

input = [1,2,3,4]

you want to shift array by 2 , start = 2

input[2:] = [3,4]

input[:2] = [1,2]

newlist = [3,4,1,2]

formatkaka
  • 1,278
  • 3
  • 13
  • 27
ffff
  • 2,853
  • 1
  • 25
  • 44
1

Here is what I would do. Get the first item of the list, delete it, then add it back to the end.

def cycle(input_list):
    first_item = input_list.pop(0)  #gets first element then deletes it from the list 
    input_list.append(first_item)  #add first element to the end
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
0

You can do this using the while or the for statements. Using for:

    newList = []
    for index in range(1, len(list)):
        newList.append(list[index])
    newList.append(list[0])

Using while:

newList = []
index = 1
while index < len(list):
    newList.append(list[index])
    index += 1
newList.append(list[0])

You'll be able to move any list one element to the left :)

Example:

def move(list):
    newList = []
    for index in range(1, len(list)):
        newList.append(list[index])
    newList.append(list[0])
    return newList

list = [1, 2, 3, 4, 5, 'd']
list = move(list)

print(list)
>>>[2, 3, 4, 5, 'd', 1]