Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand Python lambda function syntax

I don't understand how this syntax work and can't find documentation on it:

word = '123xyz567'
s = ''.join (c if c.isdigit() else ' 'for c in word)

Line 2 of code will take xyz123 and join together "123 567" into one string by passing in a lambda function to join

However, I am confused as to how this syntax works, normally a python if-else statement goes:

def example():
    for c in word:
        if c.isdigit():
            return c
        else:
            return ' ' 

Can someone either explain or direct me to documentation that explains to me the syntax structure of the lambda function passed into .join() and how I can use it properly?

like image 619
Alpha_Omega Avatar asked Mar 20 '26 13:03

Alpha_Omega


1 Answers

That's not a lambda but a generator expression.

https://www.python.org/dev/peps/pep-0289/

Almost like a list comprehension but instead a generator literal.

list = [a for a in [1,2,3]]
generator = (a for a in [1,2,3])
print(list) # [1,2,3]
print(generator) # <generator object <genexpr> at 0x7f8ee3abd6d0>
like image 118
Işık Kaplan Avatar answered Mar 22 '26 02:03

Işık Kaplan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!