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
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
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With