NEWBIE: lists as function arguments

Michael Geary Mike at DeleteThis.Geary.com
Fri Nov 7 13:59:25 EST 2003


Joe Poniatowski:
> 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']
> ...     print l2
> ...
> >>> f1(ls)
> ['word1', 'word2']
> >>> ls
> []

You may be thinking of a language that has variables and assignment
statements that change those variables. Python doesn't actually have either
of these. Instead, it has names that are bound to objects.

Your code "l2 = ['word1','word2']" *rebinds* the name "l2" to a new list
object. It doesn't affect the object that l2 was bound to before this
statement.

> However, I can return the list and it works OK:
> >>> ls = []
> >>> def f1(l2=[]):
> ...     l2 = ['word1','word2']
> ...     print l2
> ...     return l2
> ...
> >>> ls = f1(ls)
> ['word1', 'word2']
> >>> ls
> ['word1', 'word2']

This works because when you say "ls = f1(ls)" you're rebinding ls to the
object that f1() returns. You still haven't changed the list that ls was
originally bound to--ls now refers to the new object.

-Mike






More information about the Python-list mailing list