Assign value to a list using slice notation with successor

I saw people using [:] to make a copy of the list of swallows, for example:

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

I understand it. However, I saw pleura using this notation when assigning to lists, for example:

 >>> a = [1,2,3,4] >>> b = [4,5,6,7] >>> a[:] = b >>> print a [4, 5, 6, 7] >>> print b [4, 5, 6, 7] 

But I do not understand why they use [:] here. Is there a difference that I don't know?

+7
python list slice
source share
3 answers

There really is a difference between a[:] = b and a = b .

 >>> a = [1,2,3,4] >>> b = [4,5,6,7] >>> c = [8,9,0,1] >>> c = b >>> a[:] = b >>> b[0] = 0 >>> a [4, 5, 6, 7] >>> c [0, 5, 6, 7] >>> 

When you write a = b , a is a link to the same list as b: any change to b affects

when you write a[:] = b a is a list initialized by elements b: changing b will not affect


And also the difference between a[:] = b and a = b[:] .

 >>> a = [1,2,3,4] >>> b = [4,5,6,7] >>> c = a >>> a = b[:] >>> a [4, 5, 6, 7] >>> c [1, 2, 3, 4] >>> a = [1,2,3,4] >>> b = [4,5,6,7] >>> c = a >>> a[:] = b >>> a [4, 5, 6, 7] >>> c [4, 5, 6, 7] 

Using a = b[:] you create a new list with elements from b, unless another variable is specified that points to a

Using a[:] = b you change the elements of a. If another variable pointed to a, it also changed.

+7
source share

Yes, when you use [:] on the left, it changes the list in place instead of assigning a new list to a name (variable). To verify this, try the following code -

 a = [1,2,3,4] b = a a[:] = [5,4,3,2] print(a) print(b) 

You will see both "a" and "b".

To see the difference between the above and the normal purpose, try the code below:

 a = [1,2,3,4] b = a a = [5,4,3,2] print(a) print(b) 

You will see that only β€œa” has changed, β€œb” is still pointing to [1,2,3,4]

+4
source share

It is more about how he copies the list than anything. Example:

 >>> a = [1, 2, 3, 4] >>> b = [4, 5, 6, 7] >>> a = b >>> b[0] = 9 >>> a [9, 5, 6, 7] >>> b [9, 5, 6, 7] 

Here a now refers to b , so changing the value of b will also affect a .

 >>> a = [1, 2, 3, 4] >>> b = [4, 5, 6, 7] >>> a[:] = b >>> b[0] = 9 >>> a [4, 5, 6, 7] >>> b [9, 5, 6, 7] 

In the case of cutting, this is just a shallow copy of the list items, so changing b will not affect a . Hope that helps sort it out.

+2
source share

All Articles