Kartik Anand Kartik Anand -5 years ago 105
Python Question

How assignment works with python list slice

Python doc says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following doubts related to "Assignment to slices"

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

Now the output would be:

[4, 5, 3]

  1. How can something that is returning something come on the left side of expression.

  2. Yes, I read the docs and it says it is possible, now since slicing a list returns a "new" list,why is the original list being modified, I am not able to understand the mechanics behind it.

Answer Source

You are confusing two distinct operation that use very similar syntax:

1) slicing:

b = a[0:2]

This makes a copy of the slice of a and assigns it to b.

2) slice assignment:

a[0:2] = b

This replaces the slice of a with the contents of b.

Although the syntax is similar (I imagine by design!), these are two different operations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download