Search code examples
pythondefault-value

Python function with default list argument


Been experiencing this weirdness in my program. Here is a snippet of the part that is giving trouble:

#!/usr/bin python
def test_func( newList, myList=[] ):
    for t in newList:
        for f in t:
            myList.append(f)
    return myList

print test_func([[3, 4, 5], [6, 7, 8]])
print test_func([[9, 10, 11], [12, 13, 14]])

The first time the function is called, it produces

[3, 4, 5, 6, 7, 8]

The second time

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

I don't know why it does this. Are python functions static in that they retain the values passed to them in subsequent calls or am I missing something in my code?


Solution

  • Don't use mutable as keyword arguments.

    def test_func( newList, myList=None ):
        myList = [] if myList is None else myList