0

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I'm trying to write a function that randomizes a list in Python 2.7.3. The code that does it is this:

import random

def randomize_list(l, new=[]):
    if not len(l):
        return new

    print id(l), id(new)

    l1 = list(l)

    new.append(l1.pop(
        random.choice(list(range(len(l1))))
    ))

    return randomize_list(l1, new)

If I import this function, and call it multiple time, the id(new), always returns the same value, and each subsequent call to randomize_function adds items to the results of previous invocation. So, for example:

>>> a = [1,2,3,4]
>>> randomize_list(a)
35192344 35234016
16126176 35234016
16126536 35234016
16126896 35234016
[2,3,4,1]
>>> randomize_list(a)
35192344 35234016
35193488 35234016
35193344 35234016
16126608 35234016
[2,3,4,1,3,2,1,4]
... and so on

Why is this happening, and how do I fix it?

Community
  • 1
  • 1
  • 1
    Not to mention, in your particular case **you are reinventing the wheel**; the same `random` module provides a `shuffle` function already that does what you want (just make a copy first). – Karl Knechtel Jan 04 '13 at 19:25
  • @KarlKnechtel I know that. I was just exercising, and stumpled into this oddity. –  Jan 04 '13 at 19:29

0 Answers0