[Tutor] How to Pass lists by value
John Fouhy
john at fouhy.net
Tue Dec 6 02:58:10 CET 2005
On 06/12/05, Hans Dushanthakumar <Hans.Dushanthakumar at navman.com> wrote:
>
> Thanks guys
>
> Yes either of the foll solves the problem:
>
> b = junk(copy.copy(a))
>
> OR
>
> b = junk(a[:])
One thing you should be aware of --- these will both do a "shallow copy".
Example:
>>> lists = [[], [], [], []]
>>> lists2 = lists[:]
>>> lists.append('foo')
>>> lists, lists2 # This shows that lists and lists2 are different.
([[], [], [], [], 'foo'], [[], [], [], []])
>>> lists[0].append(13)
>>> lists, lists2 # Oops, but lists[0] and lists2[0] are the same!
([[13], [], [], [], 'foo'], [[13], [], [], []])
> Why is there a difference between the way the two lines (x.append("20") and
> x = "30") are handled within a function?
x = '30' will create a new (local) variable x and give it the value '30'.
x.append('20') will call the .append() method on x. Calling this
method has the side effect of changing the list x points to.
--
John.
More information about the Tutor
mailing list