2

I recently read a line of code and do not understand what is it meaning, the code is

import collections
d = collections.defaultdict(lambda : [-1, -1, -1])

I'm confused about the lambda here. I only know lamnda x: x+1. Usually, we have an argument for lambda. What if we don't have argument like this code?

Thanks a lot,

0

2 Answers 2

3

Lambda function can be used efficiently even without the lambda variable in python. General procedure for usage of lambda function is as given

in case of general function usage is

def identity(x):
    return x+1

in case of lambda

lambda x:x+1

no variable

lambda :x

will return same as x.

Without a variable the lambda function stays idle without any action an hence it can be used without a variable for getting the same answer. In precise usage of lambda without a variable of action is just an extra line of code.But it is valid.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, we can define a lambda function without any argument. But, it will be useless because there will be nothing to operate on. Let’s have a look at a simple example.

get_5 = lambda: 5

print(get_5())  # 5

Since the lambda function is always returning the same value, we can just assign it a variable. Using lambda function without any argument is plain abuse of this feature.


d = collections.defaultdict([-1, -1, -1])

produces the error:

TypeError: first argument must be callable or None

since list isin't callable, but lambda functions are callable.

2 Comments

I don't think it's fair at all to say that it's an "abuse" of the feature or "useless". A no-argument lambda function could return a random number, or otherwise give a non-constant output. Sometimes we want to pass something like that into a function or map over it.
The example in the op highlights another use: lists are mutable, so if the default value was literally [-1, -1, -1], each time it was returned it would be a reference to the same object. But almost certainly, you want a fresh copy for each time, hence the lambda which accomplishes that. (Presumably, this is why the argument must be a callable, to avoid this pitfall.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.