how does lambda work when it is not supplied with an argument

Viewed 43
pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
repl = lambda m: m.group('two').swapcase()
ser = pd.Series(['One Two Three', 'Foo Bar Baz'])
ser.str.replace(pat, repl, regex=True)
0    tWO
1    bAR
dtype: object

if the argument m in lambda is not given any parameter, how it this code able to give an output?

1 Answers

if the argument m in lambda is not given any parameter,...

Functions are objects and can be passed around before being called. This is not related specifically to lambda. It would work the same way with def:

at = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"

def repl(m): 
    return m.group('two').swapcase()

ser = pd.Series(['One Two Three', 'Foo Bar Baz'])
ser.str.replace(pat, repl, regex=True)

It is not your code that explicitly wants to call repl. The goal here is to tell str.replace what it should call during the replace operation (see docs]. So it is that API that will eventually call it, and will supply the argument for the parameter m.

Related