-1

total beginner here!

I want to make a function that take a list from the user, 3 objects list, and returns the list after moved it to the left so that the 1st object is now the last object etc.

I actually got stuck in the building the function part, as how to make the input of the list be part of the function.

the function should look like this:

def shift_left(my_list):

and the output should look like this:

>>> shift_left([0, 1, 2])
[1, 2, 0]
>>> shift_left(['monkey', 2.0, 1])
[2.0, 1, 'monkey']

Thank you!

  • This should have a good answer https://stackoverflow.com/questions/2150108/efficient-way-to-rotate-a-list-in-python – Skenvy May 24 '23 at 02:08
  • Remove the first item from the list, then add that item onto the end of the list. What is the difficulty? Do you know how to remove an item from a list? Do you know how to add an item onto the end of a list? – John Gordon May 24 '23 at 02:08
  • It's a rotate, not a shift. – Nick May 24 '23 at 04:33
  • Welcome to Stack Overflow. You ask how to pass the parameter, but you already show code that correctly does this. It appears that you are actually interested in how to write the logic of the function. Also, it appears that you want to rotate the list, not simply shift it. It is easier to [find information](https://meta.stackoverflow.com/questions/261592) when you start by clearly explaining exactly what you want to know; that helps both humans and [search engines](https://duckduckgo.com/?q=python+rotate+list). – Karl Knechtel May 24 '23 at 05:55

1 Answers1

0

An easy way to do this is to build a new list out of slices of the original list:

>>> def shift_left(items):
...     return items[1:] + items[:1]
...
>>> shift_left([0, 1, 2])
[1, 2, 0]

Note that this does not modify the original list:

>>> nums = [0, 1, 2]
>>> shift_left(nums)
[1, 2, 0]
>>> nums
[0, 1, 2]

If modifying the original list is a requirement, you could use slice assignment before returning the modified list:

>>> def shift_left(items):
...     items[:] = items[1:] + items[:1]
...     return items
...
>>> nums
[0, 1, 2]
>>> shift_left(nums)
[1, 2, 0]
>>> nums
[1, 2, 0]
Samwise
  • 68,105
  • 3
  • 30
  • 44