Ethan Layman
Ethan Layman

Reputation: 23

Using a lambda expression as a function argument

I am having trouble understanding how lambda expressions work when they are used as function arguments. For example:

import re
rep = {"hi": "hello", "ya": "you"}
text = 'hi how are ya'
keys = re.compile('hi|ya')
text = keys.sub(lambda m: rep[m.group(0)], text)
print(text)

replaces 'hi' and 'ya' with 'hello' and 'you', returning

"hello how are you"

I am confused as to why this works because we never specified what values m takes and how the re.sub() function interprets this when the first argument is supposed to be a string.

Upvotes: 2

Views: 117

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

In addition to iBug's nice answer, you say why the first argument can work with a non-string object, this is also the case with timeit, and other stuff.

Also, lambdas are equivalent to functions, so basically you're putting a function, even if you manually did a function and put the function name in it, it will work.

Note: there's a non-regex no-module way of doing this thing:

' '.join([rep.get(i,i) for i in text.split()])

Demo:

>>> rep = {"hi": "hello", "ya": "you"}
>>> text = 'hi how are ya'
>>> ' '.join([rep.get(i,i) for i in text.split()])
'hello how are you'
>>> 

Upvotes: 0

iBug
iBug

Reputation: 37227

From Python documentation:

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

You can think of lambdas as single-line functions as they're functionally equivalent, so

lambda m: rep[m.group(0)]

becomes

def unnamed_function(m):
    return rep[m.group(0)]

and m is assigned as a function argument.

Upvotes: 4

Related Questions