Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,722 Points

This piqued my interest.

Found the answer here