[Tutor] Re: Copying sequences of arbitrary dimension

Andrei project5 at redrival.net
Wed Jun 30 02:41:24 EDT 2004


Theresa Robinson <robinst <at> MIT.EDU> writes:

> I'm trying to pad a sequence of arbitrary dimension with zeros in order to
> get a sequence of a given size.  This is what I have so far, as an
> intermediate step.  I know exactly why it doesn't work: because things in
> python get passed by value, not by reference.  But can anyone suggest how

No they aren't. The distinction is between mutable objects and immutable
objects. Lists and dictionaries are mutable objects, while tuples, strings and
all kinds of numbers are immutable objects.

>>> def modifylist(alist):
...     alist.append(5)
...     
>>> def modifyint(aint):
...     aint += 5
...     
>>> l = [1,2]
>>> modifylist(l)
>>> print l
[1, 2, 5]
>>> i = 2
>>> modifyint(i)
>>> i
2

As you can see, modifyint doesn't really modify the int at all, since ints are
immutable. Instead, a new integer object is created. If we expand this example
to follow what's going on:

>>> def modifyint(aint):
...     print id(aint)
...     aint += 5
...     print id(aint)
...     
>>> id(i)
7693072
>>> modifyint(i)
7693072 <- same as id(i), so we have two names bound to the same integer object
7701072 <- different id, meaning different object (IOW, it 'points' to a
different object now)
>>> id(i)
7693072 <- i is still unmodified

> I might want to tackle this?
> 
> >>> def recursecopy(x,y):
> ...    if type(x) is IntType:
> ...       y=x

At this point you've passed an integer object to the function and you can't
modify it. You should write the function in such a way that you operate on a
list, not on an integer.

Yours,

Andrei




More information about the Tutor mailing list