6

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
javex
  • 7,198
  • 7
  • 41
  • 60

2 Answers2

11

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.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
2
[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

dawg
  • 98,345
  • 23
  • 131
  • 206
Alexey Grigorev
  • 2,415
  • 28
  • 47
  • `[a, b] = [10, 20]` is not sugar for `a, b = 10, 20` (Which is what I think you meant--`a = 10, b = 20` is not valid python.) It's roughly equivalent, but I wouldn't call it "sugar" as it doesn't make anything easier for the programmer. If anything, it makes the programmer type an additional 2 characters. – Joel Cornett Jul 14 '12 at 21:50
  • Use a semicolon then, as it is valid python and is synonymous with 2 lines of code: `a = 10; b = 20`. – Joel Cornett Jul 14 '12 at 22:09