Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #109326

Re: Beginner Question

From boB Stepp <robertvstepp@gmail.com>
Newsgroups comp.lang.python
Subject Re: Beginner Question
Date 2016-06-01 20:42 -0500
Message-ID <mailman.74.1464831757.1839.python-list@python.org> (permalink)
References <ea789a85-a90c-4ff8-ab34-4b6dc1fc6c2f@googlegroups.com> <CANDiX9Jb2_eYhz0cUBJKcKz2Z7XEmTCXXedyMiAE7jpdnEd3GA@mail.gmail.com>

Show all headers | View raw


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???

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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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