NEWBIE: lists as function arguments
Peter Otten
__peter__ at web.de
Fri Nov 7 13:53:38 EST 2003
Joe Poniatowski wrote:
> From what I've read in the tutorial and FAQ, I should be able to pass a
> mutable object like a list as a function argument, and have the caller see
> changes made to the list by the function. I must be doing something wrong
> - the function in this case assigns items to the list, but in the main
> module it's still empty:
>
> Python 2.3.2 (#1, Oct 23 2003, 11:10:37)
> [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> ls = []
>>>> def f1(l2=[]):
> ... l2 = ['word1','word2']
You are rebinding the local variable l2 to another list here.
To change the list given as the argument, do l2.append("word3")
or l2[:] = ["word1", "word2"], e. g.:
>>> def f1(alist):
... alist[:] = ['word1', 'word2']
...
>>> l1 = ['so', 'what']
>>> f1(l1)
>>> print l1
['word1', 'word2']
>>>
By the way, it is usually a bad idea to use mutable objects as default
arguments:
>>> def add(words, alist=[]):
... alist.extend(words.split())
... return alist
...
>>> for w in ["x y", "a b"]:
... print add(w)
...
['x', 'y']
['x', 'y', 'a', 'b']
>>>
I doubt this is what you expected. To default to an empty list, use
def add(words, alist=None):
if alist is None: alist = []
# ...
instead.
Peter
More information about the Python-list
mailing list