pythonkotti

Python: Left-side bracket assignment


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


Solution

  • 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.