Easy List question

Russell Blau russblau at hotmail.com
Tue Oct 5 09:19:04 EDT 2004


"Matt Williams" <matt at mwilliams.org> wrote in message
news:dd7a3c47.0410050339.efad894 at posting.google.com...
> Dear list,
>
> Can anyone explain why the append method here returns an 'unpermuted'
> list (and how to solve it_?
>
> I'm stuck?
>
> s=[]
> def permute(list):
>     len_l = len(list)
>     if len_l == 1:
>         print l
>         s.append(l)
>     for i in range (0, len_l):
>         permute(list[1:])
>         # now change position of first element with next (rotate will do
it?)
>         list.append(list.pop(0))
>         # reflect this change in the main list
>         l[len(l) - len_l:] = list
>
> l=["a","b","c"]
>
> permute(l)

When I run this script, I get the following output:

['a', 'b', 'c']
['a', 'c', 'b']
['b', 'c', 'a']
['b', 'a', 'c']
['c', 'a', 'b']
['c', 'b', 'a']
>>> print l
['a', 'b', 'c']
>>> print s
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a',
'b', 'c'], ['a', 'b', 'c']]

What were you expecting?

Here are a few clues:

When you call permute(l), "l" is a global variable that points to the list
["a", "b", "c"].  "list" is a local variable in your function that points to
the *same* list ["a", "b", "c"].  In your function, you use "list" in some
places and "l" in others, but they are both operating on the same list.
This, I strongly suspect, is not what you intended.

(Incidentally, it is legal but not advisable to use the word "list" as a
variable name, since "list" is a built-in identifier in Python, and using it
as a variable name overrides the built-in usage.)

-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list