Hi, guys, On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvst...@gmail.com> wrote: > On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <m...@sightlineinnovation.com> > wrote: >> Hi to all >> >> I have a beginner question to which I have not found an answer I was able to >> understand. Could someone explain why the following program: >> >> def f(a, L=[]): >> L.append(a) >> return L >> >> print(f(1)) >> print(f(2)) >> print(f(3)) >> >> gives us the following result: >> >> [1] >> [1,2] >> [1,2,3] >> >> How can this be, if we never catch the returned L when we call it, and we >> never pass it on back to f???
I think the OP question here is: Why it is printing the array? There is no line like: t = f(1) print t So, why the first print does print the list? The return value should be thrown away... Thank you. > > This comes up rather frequently. In fact, if you just copy your > function (Which is used in the official Python tutuorial.) and paste > it into Google you will get some relevant hits. One such is: > > https://pythonconquerstheuniverse.wordpress.com/category/python-gotchas/ > > As the link will explain the behavior you observe is a consequence of > two things: When Python assigns the default argument for the empty > list and that lists are *mutable*. > > Enjoy! > > > -- > boB > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list