0

I was wondering what the advantages of using the following code to compute the median of a list are

def median_fun(arg):
    srtd_list = sorted(arg) 
    mid = len(arg)/2   

    if len(arg) % 2 == 0:  
        return (srtd_list[mid-1] + srtd_list[mid]) / 2.0
    else:
        return srtd_list[mid] 

As opposed to using the following function?

lambda l:l.sort()or(l[len(l)/2]+l[~len(l)/2])/2.

It's my understanding that a lamda function can be used just once in a program. What are some other reasons one would use the first function as opposed to the second function?

Sharon
  • 161
  • 4
  • 1
    No, lambda function are just nameless functions. But your first and second function are not functionally equivalent, and furthermore your lambda expression is simply not easy to read. – Willem Van Onsem Oct 20 '17 at 22:38
  • The lambda expression is from code golf. But I kind of wanted a general view of why then a nameless function would be more advantageous? – Sharon Oct 20 '17 at 22:40
  • 3
    That `lambda` is clearly an example of someone using tricks to put everything on a single line. While playing code-golf can be fun, you should never seriously use something like that in production. – juanpa.arrivillaga Oct 20 '17 at 22:40
  • 4
    Anonymous functions are useful when you need to pass a function as a parameter to another function, and the function isn't needed for anything else. – Barmar Oct 20 '17 at 22:40
  • @juanpa.arrivillaga: So, the first function is basically reusable then? And thus more efficient? – Sharon Oct 20 '17 at 22:42
  • @Barmar: That makes more sense. – Sharon Oct 20 '17 at 22:42
  • 1
    If the efficiency you're talking about is the memory used to hold the function, it's only more efficient if you have the same lambda in multiple places. If you find yourself reusing a lambda, that's a sign that you should give it a name. – Barmar Oct 20 '17 at 22:44
  • @Sharon No, you can always assign the resulting lambda expression to a name, thus making it reusable (and thus defeating the whole point). I never said anything about efficiency, that comes down to the implementation details. However, I would never use the second one because it is difficult to read. Come back to that in a month an try to figure out what's going on. Code is written once, but read multiple times. – juanpa.arrivillaga Oct 20 '17 at 22:44
  • @Barmar yes, you'll note that my comment was posted soon after, and that's because while Sharon posted that I was still writing my comment. I was just *deducing* it was code golf. – juanpa.arrivillaga Oct 20 '17 at 22:50
  • I was talking about your last comment, which was posted 4 minutes later. But we can drop it. – Barmar Oct 20 '17 at 22:52

0 Answers0