prateek aryan
prateek aryan

Reputation: 39

I'm trying to rotate an array about a given index in python

case 1:

a=[1,2,3,4,5]
index k=2
a[:k],a[k:]=a[k:],a[:k]

When I swap array elements like this. I got this output.

**OUTPUT:[3, 4, 1, 2]

case 2:

b=[1,2,3,4,5]
b[k:],b[:k]=b[:k],b[k:]

but when I swap array elements like this i got this.The only difference is the order of swapping.

OUTPUT:[3, 4, 5, 1, 2]

If we swap two variables, the order of swapping doesn't make a difference. i.e a,b=b,a is same as b,a=a,b.

Why this is not working in the case of lists/array?

Upvotes: 3

Views: 153

Answers (2)

Thomas
Thomas

Reputation: 181715

The right hand side is evaluated fully before any assignments are done. Subsequently, the assignments are performed in left to right order.

So the first case evaluates to:

a[:2], a[2:] = [3, 4, 5], [1, 2]

The first assignment replaces the first two elements [1, 2] by the three elements [3, 4, 5], so now we have a == [3, 4, 5, 3, 4, 5]. The second assignment then replaces element 2 onwards by [1, 2], so it results in a == [3, 4, 1, 2].

In the second case, we have:

b[2:], b[:2] = [1, 2], [3, 4, 5]

The first assignment replaces from element 2 onwards by [1, 2] resulting in b == [1, 2, 1, 2]. The second assignment replaces the first two elements by [3, 4, 5], giving b == [3, 4, 5, 1, 2].

You may have noticed by now that this is rather tricky to think about and sometimes works mostly by accident, so I'd recommend simplifying the whole thing to:

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

Upvotes: 5

Jason Yang
Jason Yang

Reputation: 13057

If you swap two variables, there's no relation between two variables, then ok. You can find the steps as following:

>>> a=[1,2,3,4,5]
>>> k=2
>>> # a[:k], a[k:] = a[k:], a[:k]
>>> x, y = a[k:], a[:k]
>>> a[:k] = x
>>> x, a
([3, 4, 5], [3, 4, 5, 3, 4, 5])
>>> a[k:] = y
>>> y, a
([1, 2], [3, 4, 1, 2])

Upvotes: -1

Related Questions