Python: Left-side bracket assignment

1.4k views Asked by At

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

2

There are 2 answers

2
David Robinson On BEST ANSWER

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.

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

This sets child to the first element of result. It is a syntaxic sugar for list[0] = ...[0]. It also can be two element, like [a, b] = [10, 20], which is sugar for a = 10; b = 20

Also, the amount of elements from the right side should be the same for the left side, otherwise an exception will be thrown