Lambda Function String Slicing Help

I do not understand why my code is not working for the lambda function, but it works in the other format. Some please help me understand.

The exercise question is as follows, " Create a lambda function mylambda that returns the first and last letters of a string, assuming the string is at least 2 characters long."

import codecademylib

mylambda = lambda x: x[0]+x[len(x)-1] # This worked, but I don’t understand why. What does “x[len(x)-1]” even mean? I have never seen code formatted this way.

#print(mylambda(‘Hello Citizens’))

mylambda = lambda y: y[0] + y[-1] if y >= 2 #didn’t work

print(mylambda(“Hi baby”))

def name(n):#worked

if len(n) >= 2:

return n[0] + n[-1]

print(name(“Hello World”))

Hello @dev6186850664, welcome to the forums!

This means 'the item of the string or list at the index position of the length of the string or list, - 1." Basically, the last item of the list, or the last character of the string.
I hope this helps!

1 Like

Did you mean, if len(y) > 1 ?

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.