Salvatore
Salvatore

Reputation: 41

List rotation to the left in Python 3

I'm trying to create a list (b) that is list (a) rotating a's members k times to the left. I came up with this on Python 3:

n = 5
k = 4
a = [1,2,3,4,5]
b = []

for i in a:
    if (i + k) <= (n - 1):
            b.append(a[i+k])
        elif (i+k-n) < (n-1):
                b.append(a[i+k-n])      
print(b) 

But for some reason, it doesn't work since when I tell print(b) it returns a list that is exactly like list a

What am I missing here?

Upvotes: 2

Views: 1854

Answers (2)

Salvatore
Salvatore

Reputation: 41

Thanks to @RemcoGerlich for helping me see my mistake! Here's how I quickly fixed my code:

n = 5
k = 4
a = [1,2,3,4,5]
b = []
i = 0
while (i < n):
    if (i + k) <= (n - 1):
            b.append(a[i+k])
    elif (i+k-n) < (n-1):
            b.append(a[i+k-n])
    i = i+1
print(b)

Upvotes: 1

Yoav Glazner
Yoav Glazner

Reputation: 8066

A simple solution:

k = k % len(a) #we don't care about shifting x*len(a) times since it does not have any effect

b = a[k:] + a[:k]

Upvotes: 5

Related Questions