[Tutor] lambdas, generators, and the like

Keith Winston keithwins at gmail.com
Sun Jan 12 19:40:40 CET 2014


Thanks Dave, that looks like a good idea, I've played a little with
one-line generators (? the things similar to list comprehensions), but
I'm still wrapping my head around how to use them. Meanwhile I'm
reorganizing my code because I now understand better how to use
iterators (i.e. the combinations function), and I'm exploring using
tuples where I can instead of lists... if I followed an earlier
conversation properly, I think garbage collection might happen more
immediately with immutables than mutables, and this program is
crashing either Python or my entire computer every time I run it...
I'm generating a LOT of combinations.

On Sun, Jan 12, 2014 at 9:33 AM, Dave Angel <davea at davea.name> wrote:
>  Keith Winston <keithwins at gmail.com> Wrote in message:
>> I've got this line:
>>
>> for k in range(len(tcombo)):
>>     tcombo_ep.append(list(combinations(tcombo, k+1)))
>>
>> generating every possible length combination of tcombo. I then test
>> them, and throw most of them away. I need to do this differently, it
>> gets way too big (crashes my computer).
>>
> You should learn how to write and use a generator. Anytime you
>  find yourself creating a huge list, and only navigating it once,
>  consider writing a generator instead. A generator is any function
>  that has a yield in it. You can turn the loop above into a
>  one-level generator by
>
> def gen (tcombo):
>     for k in range (len (tcombo))
>           yield list (combinations (tcombo, k+1))
>
> And depending how you use the nested list, remove the call to list
>  () for some real serious space savings.
>
> (untested)
>
>
>
>> any help will be appreciated. I don't really understand lambda
>> functions yet, but I can sort of imagine they might work here
>> somehow... or not.
>>
> A lambda is seldom necessary or useful in simple programs.
>>
>
>
> --
> DaveA nr
>
>
>
> ----Android NewsGroup Reader----
> http://www.piaohong.tk/newsgroup
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Keith


More information about the Tutor mailing list