Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list basic manipulation [duplicate]

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
like image 884
2Xchampion Avatar asked Apr 01 '16 10:04

2Xchampion


3 Answers

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
like image 78
jDo Avatar answered Nov 18 '22 21:11

jDo


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]

like image 45
Faiz Halde Avatar answered Nov 18 '22 23:11

Faiz Halde


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
like image 28
Mark Skelton Avatar answered Nov 18 '22 21:11

Mark Skelton