Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does assignment work with list slices?

Tags:

python

list

slice

Python docs says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following questions 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.
like image 452
Kartik Anand Avatar asked Oct 16 '22 23:10

Kartik Anand


People also ask

What is slice assignment?

Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation.

Does slicing a list create a copy?

Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.

What does list slicing do?

List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

Can we use slice in list?

As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable.


1 Answers

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.

like image 149
NPE Avatar answered Oct 19 '22 13:10

NPE