What am I missing here ? If List size is greater than 5, I need last element, else first element.
fn = lambda *d: d[-1] if len(d) > 5 else d[0]
print map(fn,[1,2,3,4,5,6,7,8,9,10])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Your use of map is incorrect. Your example is the equivalent of:
print [fn(1), fn(2), fn(3), ...]
You have a second problem with your use of *d in your lambda. This is special syntax for calling a method with multiple arguments. d is now a tuple of all your arguments, so if you call:
>>> fn = lambda *d: d
>>> fn([1, 2, 3])
([1, 2, 3],)
This is your code:
In [124]: n = lambda *d: d[-1] if len(d) > 5 else d[0]
In [125]: map(n,[1,2,3,4,5,6,7,8,9,10])
Out[125]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But this is what it is actually doing:
In [126]: n = lambda *d: d
In [127]: map(n,[1,2,3,4,5,6,7,8,9,10])
Out[127]: [(1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,)]
For your purpose, this should be sufficient:
In [132]: d = [1,2,3,4,5,6,7,8,9,10]
In [133]: d[-1] if len(d) > 5 else d[0]
Out[133]: 10
In [1]: print map.doc map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).
this would do what you want:
fn = lambda *d: d[-1] if len(d) > 5 else d[0]
map(fn, [[1,2,3,4,5,6,7,8,9,10]])
You can't use map here. this lambda link is helpful to you
As you can see, fn() and gn() do exactly the same and can be used in the same ways. Note that the lambda definition does not include a "return" statement -- it always contains an expression which is returned. Also note that you can put a lambda definition anywhere a function is expected, and you don't have to assign it to a variable at all.
You try this:
L = [1,2,3,4,5,6,7,8,9,10]
fn = lambda d: d[-1] if len(d) > 5 else d[0]
print fn(L)
10
it also give you same output.
def gn(d): return d[-1] if len(d) > 5 else d[0]
print gn(L)
10
mapto call a function that works on the whole list rather than each element? Justprint fn([...]).