Simple del[] list question

Tim Hochberg tim.hochberg at ieee.org
Wed Apr 26 13:46:25 EDT 2000


"Matthew Hirsch" <meh9 at cornell.edu> wrote:
> Hi All,
>
> What is going on here?
>
> This leaves a intact.
>
> >>> a=[[1,2,3],[4,5,6]]
> >>> b=a[:]

This makes a _shallow_ copy of a. It's probably more obivous what's going on
if we name the sublists in a"

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> a = [x,y]  # This is equivalent to a=[[1,2,3],[4,5,6]]
>>> b = a[:]

Since this makes a shallow copy, b is a new list containing x and y. In
other words, in this case, b = a[:] is equivalent to b = [x, y].

> >>> del b[0]
> >>> b
> [[4, 5, 6]]

This removes x from b, but since a is a copy of b it has no effect on a.

> >>> a
> [[1, 2, 3], [4, 5, 6]]
>
>
> This also changes a.
>
> >>> a=[[1,2,3],[4,5,6]]
> >>> b=a[:]
> >>> del b[0][0]

Here del b[0][0] is equivalent to del x[0]. Since a and b share x, this
effects both arrays.

> >>> b
> [[2, 3], [4, 5, 6]]
> >>> a
> [[2, 3], [4, 5, 6]]
>
> Why did a change?  Why suddenly when you go to two dimensions does the
> behavior change?

Hope the helps,

-tim






More information about the Python-list mailing list