4

I am trying to understand the code below:

from functools import reduce
reduce(lambda d, i: (i[0] < 7 and d.__setitem__(*i[::-1]), d)[-1], [{}, *{1:2, 3:4, 5:6, 7:8}.items()])   

The part that I don't understand is the *.

 [{}, *{1:2, 3:4, 5:6, 7:8}.items()]

returns:

[{}, (1, 2), (3, 4), (5, 6), (7, 8)]

Now if i run in isolation

*{1:2, 3:4, 5:6, 7:8}.items()

it returns an error : "File "cell_name", line 4 SyntaxError: can't use starred expression here". However I am able to run the code without * just fine as a one-line code and returns:

dict_items([(1, 2), (3, 4), (5, 6), (7, 8)])

I have googled it and in https://medium.com/understand-the-python/understanding-the-asterisk-of-python-8b9daaa4a558 it seems related to unpacking containers, but this one is used in arrays.

However in the full lambda, the * seems necessary and throws an error "'dict_items' object does not support indexing" without the *.

Anyone understand this syntax jargon? Thanks for any help.

Earl
  • 420
  • 5
  • 16
  • It's being used in the same way as the article, it's just "extended iterable unpacking" which works in literals now – juanpa.arrivillaga Mar 14 '19 at 00:07
  • 1
    I don't know where you found that horrible one-liner, and I can respect your desire to understand it, but *please* don't actually use that piece of junk in your code. Throw it in the trash, where it belongs. – Aran-Fey Mar 14 '19 at 00:08
  • I am trying to find a way to have a multi-line lambda and I am trying to explore an answer given in https://stackoverflow.com/questions/1233448/no-multiline-lambda-in-python-why-not – Earl Mar 14 '19 at 00:11
  • 1
    Don't. Just use a regular function. – Aran-Fey Mar 14 '19 at 00:12
  • Read this answer: https://stackoverflow.com/a/34166505/5014455 – juanpa.arrivillaga Mar 14 '19 at 00:18
  • I too second the recommendation not to use that awefuo one-liner. You don't *need* multiline lambdas. Just use a regular function definition. Quite frankly using a side effect in `reduce` seems designed to piss everyone off – juanpa.arrivillaga Mar 14 '19 at 00:21
  • Thanks everyone. I just started python coming from C# background and we love our anonymous functions over collections but it seems i should not do that in Python. I will look at the original question to understand this asterisk syntax. Thanks Again. – Earl Mar 14 '19 at 00:28

0 Answers0