[Tutor] Python program to remove first four even numbers from a list

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 17 19:20:11 EDT 2021


On 17/10/2021 19:15, Finn Mason wrote:

>> By writing this :
>> lst[:] = remove4even(lst)   # here i am modify the existing list lst
>>
>> But by doing this
>>
>> lst = remove4even(lst)     #  Now variable lst is reassigned, so it is a
>> different object
> 
> 
> I can see how you reached that conclusion. However, you're wrong about the
> slice.
> 
> When you slice a sequence, it *returns a copy* of the sequence. 

That's true when the slice is an rvalue.

But if the slice is on the left side then slice assignment
takes place which replaces the slice with the new value.
It does not create a copy.

lst = [1,2,3,4,5,6,7,8,9]
lst[3:4] = [0,1,2]
print(lst)
[1, 2, 3, 0, 1, 2, 5, 6, 7, 8, 9]

The new values are inserted no copies are made.

So when you do

lst[:] = ...

You are *replacing* the entire list.
But because the OP is replacing it with another list
he is copying the new list into the old list.

> * lst[:]
> * lst.copy()
> * copy.copy(lst) # Using the built-in copy module
> * list(lst)
> * [x for x in lst]

as rvalues yes, but most of these cannot be used
as lvalues, whereas the slice can. But it works
differently on the left than on the right.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list