[Tutor] modifying lists of lists

eryksun eryksun at gmail.com
Thu Oct 4 07:22:19 CEST 2012


On Wed, Oct 3, 2012 at 11:52 PM, Ed Owens <eowens0124 at gmx.com> wrote:
>
> py> H = [[1, 2]]
> py> J = [H[0]]
> py> H[0][1] = copy.deepcopy(H[0][0])
>
> How do I decouple these references?

You can use the slice H[0][:] to get a shallow copy of the H[0] list.
By "shallow copy" I mean you get a new list that contains the items of
the source list. You can mutate this new list without changing the
source list.

Returning to your first example:

    >>> H = [[(0, 1), (2, 3)], [(1, 2), (3, 4)]]

Insert a shallow copy of H[0] at index 1:

    >>> H.insert(1, H[0][:])
    >>> H
    [[(0, 1), (2, 3)], [(0, 1), (2, 3)], [(1, 2), (3, 4)]]

The new list at H[1] is independent of H[0]:

    >>> H[1].pop(1)
    (2, 3)
    >>> H
    [[(0, 1), (2, 3)], [(0, 1)], [(1, 2), (3, 4)]]


More information about the Tutor mailing list