0

I am trying to rotate the array by using following function:

def rotLeft(a,d):
    temp=[]
    temp.append(a[0:-1])
    temp.insert(0,a[-1])
    return temp

I should get output as 5 1 2 3 4

but I am getting 5,[1,2,3,4]

how to solve this problem

2 Answers2

0

You must use Use .extend() instead of .append() as .append() and .insert() is for adding elements while .extend() is to merge two lists:

def rotLeft(a,d):
    temp=[]
    temp.extend(a[0:-1])
    temp.insert(0,a[-1])
    return temp

print(rotLeft([1,2,3,4,5], 1))

output:

[5, 1, 2, 3, 4]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

You need to use temp.extend, not temp.append. The latter just adds one element to temp, the list [1,2,3,4] - this is why you end up with a nested list. extend on the other hand works as if each element from [1,2,3,4] is appended to temp.

timgeb
  • 76,762
  • 20
  • 123
  • 145