Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Mike Brooks
Mike Brooks
3,389 Points

Setting argument = None causes no accumulation

From the Python tutorial I excerpted the following code:

def f(a, L=[]):
    L.append(a)
    return L

def f2(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L


print(f(1))
print(f(2))
print(f(3))

print(f2(1))
print(f2(2))
print(f2(3))

Which yields the following results:

[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]

It was showing how in the case of function f(), the contents of the L list are accumulating with each call and how if you alternatively in f2() set L = None it does not.

Maybe this is just something I should take as True but what about setting L = None overrides the notion that the argument is only instantiated at function definition time.

Thanks,

1 Answer

Samuel Ferree
Samuel Ferree
31,721 Points

This piqued my interest.

Found the answer here