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

Richard Damon Richard at Damon-Family.org
Sun Oct 17 16:13:33 EDT 2021


On 10/17/21 3:35 PM, Alan Gauld via Tutor wrote:
> On 17/10/2021 16:03, Manprit Singh wrote:
>> Dear sir,
>>
>> 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
> But an identical object. And the first method copies the object
> returned from the function before throwing it away whereas the
> direct assignment is much less processor (and time) intensive
> and achieves the same result.
>
> The slicing approach would be the best one if you wanted to
> replace part of the original list with the returned values,
> but if you are going to replace the whole list you might
> as well just reassign the variable.
>
The difference would be if you had done:

copy = lst

lst[:] = ...


then copy is a copy of the new value in lst


but if you did:

copy = lst

lst = ...


Then copy is a copy of the OLD value in lst, and only lst is the new value.

Not to says this is good practice, but something to think of.

-- 
Richard Damon



More information about the Tutor mailing list