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

Finn Mason finnjavier08 at gmail.com
Sun Oct 17 14:15:58 EDT 2021


On Sun, Oct 17, 2021, 9:04 AM Manprit Singh <manpritsinghece at gmail.com>
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


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. In Python,
all of these expressions are equivalent:

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

We can check with the is operator, which checks if two objects refer to the
same value in memory:

\>>> lst[:] is lst
False

The expression with a slice is no different from the one without a slice
(and actually perhaps worse, if we're really worried about memory).

One of the great (or horrible, depending on who you ask) things about
Python is that you rarely have to worry about memory, since it's garbage
collected for you. Only make a copy when you don't want to mutate the
original mutable iten.

--
Finn Mason


More information about the Tutor mailing list