1

I'm asked to write a function rotate_left3(nums) that takes a list of ints of length 3 called nums and returns a list with the elements "rotated left" so [1, 2, 3] yields [2, 3, 1].

The questions asks to rotate lists of length 3 only. I can easily do this by the following function (as long as the lists will only be of length 3):

def  rotate_left3(nums):
    return [nums[1]] + [nums[2]] + [nums[0]]

However, my question is, how do I do the same operation but with lists of unknown lengths?

I have seen some solutions that are complicated to me as a beginner. so I'd appreciate if we can keep the solution as simple as possible.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Moh'd H
  • 247
  • 1
  • 4
  • 16
  • I think it's *no duplicate* because it asks for rotating by exactly one. This is a special case with special properties, for example concerning performance, that deserves its own answers. – Wolf Oct 17 '19 at 10:20

1 Answers1

2

Let's create a list:

>>> nums = range(5)

Now, let's rotate left by one position:

>>> nums[1:] + nums[:1]
[1, 2, 3, 4, 0]

If we wanted to rotate left by two positions, we would use:

>>> nums[2:] + nums[:2]
[2, 3, 4, 0, 1]
John1024
  • 109,961
  • 14
  • 137
  • 171