+ 2

Python function

def func(a,L=[]): L.append(a) return L d=func(1) print(d) e=func(2) print(d) why is the output for the second print 1 2 instead of 1 i know that the e should be 1 2 but why does it also affect the d variable

4th Mar 2018, 8:34 AM
John
John - avatar
2 odpowiedzi
+ 1
if u use list...and appending to it then...it gets affected.. if u use variable like int etc. it wont get affacted..
4th Mar 2018, 9:22 AM
sayan chandra
sayan chandra - avatar
0
The list L is saved in the function and will grow every time the function is called. To create a new empty list use this code: def func(a): L = [] L.append(a) return L
4th Mar 2018, 9:00 AM
Sebastian Keßler
Sebastian Keßler - avatar