Is it possible to use a try except block inside of a lambda function? I need the lambda function to convert a certain variable into an integer, but not all of the values will be able to be converted into integers.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Nope. A Python lambda can only be a single expression. Use a named function.
It is convenient to write a generic function for converting types:
Then you can write your lambda:
You could also write
tryconvert()so it returns a function that takes the value to be converted; then you don’t need the lambda:Now
tryconvert(0, int)returns a functionconvert_0_intthat takes a value and converts it to an integer, and returns0if this can’t be done. You can use this function right away (not saving a copy):Or save it to call it later: