On Wed, Sep 9, 2020 at 6:18 PM Nicholas Cole <nicholas.c...@gmail.com> wro
>
> On Wed, Sep 9, 2020 at 8:52 AM Chris Angelico <ros...@gmail.com> wrote:
>
> [snip]
> > And if you absolutely have to mutate in place:
> >
> > items[:] = [i for i in items if i not in "bcd"]
>
> How does that work to mutate in place?

Technically it constructs a new filtered list, and then replaces the
contents of the original list with the filtered one. That's
effectively an in-place mutation; any other reference to that same
list will see the change. Compare:

a = list(range(20))
b = a
a = [n for n in a if n % 3]
print(a)
print(b)

You'll see that a and b now differ. But if you use slice assignment:

a[:] = [n for n in a if n % 3]

you'll see that the two are still the same list (and "a is b" will
still be True). It's replacing the contents, rather than rebinding the
name.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to