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
Thananjaya Chakravarthy
4,672 Pointsdef f(x,l=[]): for i in range(x): l.append(i*i) print(l) f(2) f(3,[3,2,1]) f(3)
list 'l' is declared as empty in define function. How come the output for f(3) has values for which f(2) is called.. The output of this code is [0, 1] #for f(2) [3, 2, 1, 0, 1, 4] #for f(3,[3,2,1]) [0, 1, 0, 1, 4] #for f(3)... but its has the value of f(2)... but the list is been declared as empty inside the function??
1 Answer
Kenneth Love
Treehouse Guest TeacherDon't use mutable types as default arguments. They hang around and you get these nasty side effects.
def f(x, l=None):
l = l or []
for i in range(x):
l.append(i*i)
print(l)
f(2)
f(3,[3,2,1])
f(3)
Thananjaya Chakravarthy
4,672 PointsThananjaya Chakravarthy
4,672 PointsThanks sir... Is it possible that list related to one function call will store the values and show it in next function call..?