Python – Lambda aka Anonymous Functions r cool

I have never used something like this to my knowledge, but these are pretty slick. I was studying and these came up, afterwards decided I wanted more examples and watched some YT. Socratica an excellent YouTube channel made another fun video with a couple excellent examples. Look at that slick looking authors.sort() line 3, uses .sort(), lambda, slicing, and lower() which are each their own lesson. I am a huge fan of short one liners, so Lambdas are something I will be exploring more.

# Seen on Socratica YT, sorts a list by authors last name
authors = ['Ray Madbury', 'Steven Kang', 'Ryan H Burke', 'Steven C Pressmany', 'Isaac Asimovie', 'Tony Starker']
authors.sort(key=lambda name: name.split(' ')[-1].lower())
print(authors)

# Few more of my practice scripts below
# calculate the cube of the input and output it
 x = int(input())
 y = (lambda z:z**3)(x)
 print(y)

# two vars, this one helped me understand, remove the 'lambda x, y:' and nothing works.
mysum = lambda x, y:x + y 
print('My sum is:',mysum(7,8))

#  simple but tricky 'looking'
g, h = [1,4,7], lambda x: x + 8
print(h(sum(g)))

Leave a Comment