I was doing a simple problem in python of shifting an array to the left using python 3.0 for the problem I have I only need to have a length of 3 for the array. For example if my array is [1, 2, 3] after the shift it should read [2,3,1]. My code works but I was wondering if anyone could guide me to making it more efficient, as well as doing it for any array length if possible. My issue is that I don't think I know how to shift all the elements at once, instead I shift all the elements after the first element, and then I append the first element to the array after the loop.
[1, 2, 3]
[2,3,1]
def rotate_left3(nums): shifted_nums=[] i=len(nums) for j in range(i): shifted_nums=nums[j-1:] var=nums[0] shifted_nums.append(var) return shifted_nums
What about this? simply copy the array without the first element first.
def rotate_left3(nums): shifted_nums = nums[1:] shifted_nums.append(nums[0]) return shifted_nums
1.4m articles
1.4m replys
5 comments
57.0k users