# [Tutor] modifying lists of lists

eryksun eryksun at gmail.com
Thu Oct 4 19:17:54 CEST 2012

```On Thu, Oct 4, 2012 at 7:21 AM, Dave Angel <d at davea.name> wrote:
>
> This is how eryksun knew that a shallow copy was good enough.  And for a
> shallow copy, using the slice notation is perfect.
>
>>>> J42 = [H[:1]]
>>>> print J42[0]
> [(1, 2)]
>>>> print id(J42[0])
> 13964568
>
> (Note that my shallow copy is not quite what eryksun was using.  His
> lost one level of the nesting, by doing both the subscript and the slice.)
> Now, since the id is different, you won't get the problem you saw first.

>>> H = [[1, 2]]

Copy the list [1,2] at H[0] and nest it in a list:

>>> J = [H[0][:]]
>>> J
[[1, 2]]

Modify the original list:

>>> H[0][1] = H[0][0]
>>> H
[[1, 1]]

The copy is unchanged:

>>> J
[[1, 2]]

Seems OK to me. Then I switched to the Ed's original problem. This
problem no longer uses another named list (J in the above), but it's
similar. Here's H:

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

The problem is to insert a copy of list H[0] at index 1 of H. At a
minimum it has to be shallow copied because later Ed wants to modify
it (i.e. H[1].pop(1)) without affecting H[0]. Copying H up to index 1
would preserve an undesired nested structure, so you'd have to
subscript, but then the subscripted value would be the original H[0]
list. You actually have to copy H[0], either by slicing with H[0][:],
or calling the list constructor with list(H[0]), or using
copy.copy(H[0]).
```