Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #109332
| From | Igor Korot <ikorot01@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Beginner Question |
| Date | 2016-06-02 00:21 -0400 |
| Message-ID | <mailman.75.1464841301.1839.python-list@python.org> (permalink) |
| References | <ea789a85-a90c-4ff8-ab34-4b6dc1fc6c2f@googlegroups.com> <CANDiX9Jb2_eYhz0cUBJKcKz2Z7XEmTCXXedyMiAE7jpdnEd3GA@mail.gmail.com> <CA+FnnTwv80nimQY-FXDY8KrZ1gbMTqydGtSwBQt_6it8ztZCXg@mail.gmail.com> |
Hi, guys, On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvstepp@gmail.com> wrote: > On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <mrak@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Beginner Question Marcin Rak <mrak@sightlineinnovation.com> - 2016-06-01 17:55 -0700
Re: Beginner Question boB Stepp <robertvstepp@gmail.com> - 2016-06-01 20:42 -0500
Re: Beginner Question Marcin Rak <mrak@sightlineinnovation.com> - 2016-06-02 06:10 -0700
Re: Beginner Question Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2016-06-02 13:53 +1000
Re: Beginner Question Igor Korot <ikorot01@gmail.com> - 2016-06-02 00:21 -0400
Re: Beginner Question Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2016-06-02 15:20 +1000
Re: Beginner Question Igor Korot <ikorot01@gmail.com> - 2016-06-02 09:38 -0400
Re: Beginner Question sohcahtoa82@gmail.com - 2016-06-02 11:02 -0700
csiph-web