Basic Python manipulation

So, I tried to write a very basic function that can move every item in the list one index before. And I think that in fact I am very close to the result that I want.

For example, if the list

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

I want it to be so on

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

Reality of my code

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

Here is my code, I just don’t know what happens after many random attempts to change the code ...

Thanks 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 
+5
source share
4 answers

You can do this (in place):

 l.append(l.pop(0)) 

In the form of a function (makes a copy):

 def cycle(l): ret = l[:] ret.append(ret.pop(0)) return ret 
+9
source

As a python developer, I really can't type this one liner

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

where start is the amount by which you must rotate the list

Example:

input = [1,2,3,4]

you want to change the array to 2 , start = 2

input[2:] = [3,4]

input[:2] = [1,2]

newlist = [3,4,1,2]

+2
source

Here is what I will do. Get the first element of the list, delete it and add it 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 
+1
source

You can do this using while or 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 can move any list to one item on 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] 
0
source

Source: https://habr.com/ru/post/1246225/


All Articles