Lambda question

Mel mwilson at the-wire.com
Sat Jun 4 14:21:51 EDT 2011


jyoung79 at kc.rr.com wrote:

> I was surfing around looking for a way to split a list into equal
> sections.  I came upon this algorithm:
>  
>>>> f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
>>>> f("Hallo Welt", 3)
> ['Hal', 'lo ', 'Wel', 't']
>  
> http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-
evenly-s
> ized-chunks-in-python/312644
>  
> It doesn't work with a huge list, but looks like it could be handy in
> certain
> circumstances.  I'm trying to understand this code, but am totally lost. 
> I know a little bit about lambda, as well as the ternary operator, but how
> does this part work:
>  
>>>> f('dude'[3:], 3, []+[('dude'[:3])])
> ['dud', 'e']
>  
> Is that some sort of function call, or something else?  I'm guessing it
> works recursively?

Yeah, recursive.

f('dude', 3) 

evaluates to

f('e', 3, []+['dud']) if 'dude' else []

which evaluates to

f('', 3, []+['dud']+['e']) if 'e' else []+['dud']

which evaluates to

[]+['dud']+['e']

because the if...else finally takes the second branch since the x value is 
now an empty string.  

I've left the list additions undone .. tracing the actual data objects would 
show plain lists.  One of the disadvantages of lambdas is that you can't 
stick trace printouts into them to clarify what's happening.  Rewriting the 
thing as a plain def function would be instructive.

	Mel.






More information about the Python-list mailing list