how can i copy a sublist

Alex Martelli aleaxit at yahoo.com
Thu Mar 1 16:22:45 CET 2001


"Daniel Orlowski" <daniel.orlowski at bg-sys.de> wrote in message
news:3A9E4C6F.E2DD63C3 at bg-sys.de...
> Hi,
>
> i try to copy a sublist from list "a" to list "b". After that i alter a
> value in "b" and oops! value in "a" is also altered.
> so it looks like that:
> >>> a=[[1,2],[3,4]]
> >>> b=[]
> >>> b.append(a[0])
> >>> b
> [[1, 2]]
> >>> b[0][0]=3
> >>> a
> [[3, 2], [3, 4]]
>
> how can i copy a sublist without
> "get_a_value_from_a_list_and_put_it_into_another"

I'm not quite sure what you mean, but, anyway,
    b.append(a[0][:])
will, assuming a[0] is a sequence, append to b
a _copy_ (a shallow-copy) of that sequence, rather
than a reference to the _same_ sequences as a[0]
refers to.


In general, using xxx[:] (a "slice everything"
request) works to get a shallow-copy of a sequence
to which xxx refers to (for any xxx -- it does not,
of course, matters if it's a name, an index into
some other sequence, an index into a mapping, &c).

For more general copying (deep rather than shallow,
or copying of other object kinds) see module copy.


Alex






More information about the Python-list mailing list