3

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?

3
  • The left-hand variables or slices are assigned from left to right from the right-hand tuple. If first assignment changes indexes in the list this affects the second. Commented Jul 6, 2020 at 9:42
  • 1
    Well think about the steps of what a[:k],a[k:]=a[k:],a[:k] does. Commented Jul 6, 2020 at 9:44
  • If you're determined to make ik work (and frustrate your coworkers) you could do a[:k], a[len(a)//2:] = a[k:], a[:k] Commented Jul 6, 2020 at 10:16

2 Answers 2

5

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]
Sign up to request clarification or add additional context in comments.

Comments

-1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.