Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Left-side bracket assignment

Tags:

python

kotti

So I found this code inside Kotti:

[child] = filter(lambda ch: ch.name == path[0], self._children)

And I was wondering: What do the left-hand square brackets do? I did some testing in a python shell, but I can't quite figure out the purpose of it. Bonus question: What does the lambda return? I would guess a tuple of (Boolean, self._children), but that's probably wrong...

like image 958
javex Avatar asked Jul 14 '12 21:07

javex


1 Answers

This is list unpacking, of a list with only a single element. An equivalent would be:

child = filter(lambda ch: ch.name == path[0], self._children)[0]

(The exception would be if more than one element of self._children satisfied the condition- in that case, Kotti's code would throw an error (too many values to unpack) while the above code would use the first in the list).

Also: lambda ch: ch.name == path[0] returns either True or False.

like image 148
David Robinson Avatar answered Sep 21 '22 19:09

David Robinson