Beginner Question

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Thu Jun 2 14:02:49 EDT 2016


On Thursday, June 2, 2016 at 6:38:56 AM UTC-7, Igor Korot wrote:
> Steven,
> 
> On Thu, Jun 2, 2016 at 1:20 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> > On Thursday 02 June 2016 14:21, Igor Korot wrote:
> >
> >> Hi, guys,
> >>
> >> On Wed, Jun 1, 2016 at 9:42 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> >>> On Wed, Jun 1, 2016 at 7:55 PM, Marcin Rak <mrak at 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?
> >
> > Because he calls the function, then prints the return result.
> >
> > print(f(1))
> >
> > calls f(1), which returns [1], then prints [1].
> >
> > Then he calls:
> >
> > print(f(2))
> >
> > which returns [1, 2] (but he expects [2]), then prints it. And so on.
> >
> >
> >> There is no line like:
> >>
> >> t = f(1)
> >> print t
> >
> > Correct. But there are lines:
> >
> > print(f(1))
> > print(f(2))
> > print(f(3))
> 
> I think you missed the point.
> 
> Compare:
> 
> def f(a, L=[]):
>      L.append(a)
>      return L
> 
> print(f(1))
> print(f(2))
> print(f(3))
> 
> vs.
> 
> def f(a, L=[]):
>      L.append(a)
>      return L
> 
> t = f(1)
> print t
> t = f(2)
> print t
> t = f(3)
> print t
> 
> For people that comes from C/C++/Java, the first syntax is kind of weird:
> you return a value from the function but the caller does not save it anywhere.
> Especially since the return is not a basic type and most of them are
> not familiar
> with scalar vs list context (sorry for the Perl terminology here)
> 
> Thank you.
> 
> 
> >
> >
> >
> > --
> > Steve
> >
> > --
> > https://mail.python.org/mailman/listinfo/python-list

I came from C/C++/Java, and the first syntax makes perfect sense to me.  You're just taking the result of a function and directly passing it as a parameter to another.  There's nothing confusing about that.  C/C++/Java let you do it.


More information about the Python-list mailing list