Python: left side 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 square brackets do? I did some testing in the python shell, but I cannot fully understand its purpose. Bonus question: what does lambda return? I would suggest a tuple (Boolean, self._children) , but this is probably wrong ...

+4
source share
2 answers

This is a list unpack list with only one item. The equivalent would be:

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

(An exception would be if more than one element from self._children met the condition - in this case, the Kotti code would throw an error (too many values ​​to unpack), while the above code would use the first one in the list).

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

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

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

In addition, the number of elements on the right side must be the same for the left side, otherwise an exception will be thrown

+2
source

All Articles