1

I was solving a programming puzzle and came across this solution by someone. I don't understand why the * is used.

a = [*map(len,input().replace(" ","").replace("12","1 2").replace("21","2 1").split(" "))]
ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
govind
  • 11
  • 2
  • 1
    See [Unpacking argument lists](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists) – benvc Mar 22 '19 at 19:34
  • 1
    @Nathan: Bad dupe target; this particular kind of unpacking isn't touched on until about 10 answers and 27 pages down on that question. – user2357112 supports Monica Mar 22 '19 at 19:35
  • 2
    I don't understand why it's used, either. `list(map(...))` would have been clearer. – chepner Mar 22 '19 at 19:39
  • 1
    [asterisk in tuple, list and set definitions, double asterisk in dict definition](https://stackoverflow.com/q/36980992/364696) is specific to PEP 448's unpacking generalizations though, so I've made it the sole dupe target. – ShadowRanger Mar 22 '19 at 19:40
  • Okay, I agree the usage of unpacking into a list is different enough from expanding arguments for a function that I was a bit hasty. Thanks for finding a better target – Nathan Mar 22 '19 at 19:41
  • @chepner: It's ever-so-slightly shorter/faster? :-) I happen to like the unpacking syntax a lot, and I think it's mostly a matter of newness (and to an extent, difficulty of finding documentation of syntactic elements) that makes it seem unclear. – ShadowRanger Mar 22 '19 at 19:41
  • If the list were a combination of one or more `map`s and/or additional items, something like `[*map(...), *map(...), 3, 5]` would make sense, since I think the alternatives would be `list(chain(map(...), map(...), [3,5]))` and `list(map(...)) + list(map(...)) + [3,5]`. – chepner Mar 22 '19 at 19:47
  • @chepner: Yeah, the `list(chain(map(...), map(...), [3,5]))` approach is the only one-liner solution with `O(n)` performance prior to the unpacking generalizations. With PEP 448, `[*map(...), *map(...), 3, 5]` is faster (and avoids the need for an import). Either way, `list(map(...)) + list(map(...)) + [3,5]` is a bad choice since it's a [form of Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Schlemiel_the_Painter's_algorithm), where a huge output from the left hand side must be copied to three progressively larger `list`s before it actually produces the final result. – ShadowRanger Mar 22 '19 at 19:57

0 Answers0