I tried various permutations of sumfcn = lambda *args: 0.+(map(int,args)) and got various traceback messages. I found that you can do the following eval('+'.join(map(str,(3,4,5,6))))
I'm not sure anybody would do this in real life, but it's just a rather neat python kind of thing that you could make more general like this >>> sumfcn = lambda *args: eval('+'.join(map(str,args))) >>> sumfcn(3,4,5,6,7) 25 >>> sumfcn(3,4,1) 8 >>> sumfcn("3","2") 5
I'm going to throw it in my collection of utility functions because, sometimes, you just need to sum a list of numbers.
Anybody got any stupid Python tricks they would like to share?
I think it might be even simpler if you used reduce().
I did something a somewhat similar thing using eval() with environment variabes, where certain features could be configured with boolean logic, like breakfastEnabled='HAM and EGGS and not SPAM'. Then at runtime, the environment variables HAM, EGGS and SPAM are set to either 1 or 0, based on some other installation parameters. They are substituted into this string, then evaluated and that determines whether a specific feature is enabled. Python makes these kinds of things pretty easy to do.
Elegancy is a matter of personal taste and does not have to do anything with how the code performs.
If you post this in comp.lang.python you will get a dozen replies on how this performs less when compared to using 'operator add()' etc.
I once posted a rather 'elegant' looking solution for printing a multilist using lambda and reduce (it had multiple lambdas' and reduces' and looked very elegant to me!) and got chaffed by Alex Martelli on how it performs worse when compared to his solution.
So I would advise you from my experience to skip the 'elegancy' part of code since it does not have to do anything with how the code works.