The world’s leading publication for data science, AI, and ML professionals.

Lambda Functions with Example and Error Handling

Writing immediate functions in dirty ways. It is not recommended for all situations, however, it's convenient

Lambda Functions and Error Handling. Photo by Christina Morillo from Pexels
Lambda Functions and Error Handling. Photo by Christina Morillo from Pexels

TIPS FOR PYTHON DEVELOPERS

Prerequisites

Before going through this, you need to be familiar with defining your own function in Python; otherwise, you will get lost in the middle. The articles below will give you more information on how to define your own function.

Writing Your Own Functions

Scope of Variable and LEGB Rule

Function Arguments: Default, Keyword, and Arbitrary


Lambda function syntax. Image by Author
Lambda function syntax. Image by Author

There is a more agile way to write functions on the fly, and these are called lambda functions. It is because we use the keyword lambda. For example, we write a function called raise_number_to_power as a lambda function. After the keyword lambda, we specify the names of the arguments, which is x and y. Then, we use a colon, followed by the expression that defines what we wish the function to return.

Lambda functions allow you to write immediate functions in dirty ways, so I wouldn’t recommend you to use them all the time, but there are situations when they can come in very helpful. For example, the map function, which takes two arguments. A function and a sequence such as a list, and the function over all elements of the sequence.

Lambda in the map function. Image by Author
Lambda in the map function. Image by Author

We can carry lambda functions to map without even naming them, and in this case, we refer to them as anonymous functions. For instance, we use a map on a lambda function that squares all elements of a list, and you will store the result in a square variable. While printing the square variable, it reveals that it is a map object. To see what it contains, we use the function list to turn it into a list and print the results. As expected, it’s a list containing the squares of the elements in the original list.


Error Handling

When you misuse a function, it should throw you an error. For example, check out the function float that returns a floating-point from a number or string. When you pass the function float an integer value, the corresponding float is returned. Similarly, if you give it the string 8.7 it will return the float value.

Use function incorrectly will returns error. Image by Author
Use function incorrectly will returns error. Image by Author

However, if you pass it the string hello, Python will throw an error showing you that it couldn’t convert the string to float. In this case, it threw a ValueError, and there are many types of errors. When we write our functions, we may wish to discover particular problems and write specific error messages. Let’s check out the user-defined function that computes the square root of a number. It works as expected with integers. What are the results if we pass it a string such as hello? It will throw you an error corresponding to a line of code within the function definition.

Convert string to float error. Image by Author
Convert string to float error. Image by Author

This error says it was some TypeError, but the message may not be particularly helpful to a user of our function, so we should attempt to provide useful error messages for the functions we write.

The primary method to catch such exceptions is the try-except clause, in which Python tries to run the code following a try, and if it can, all is well. If it cannot work due to an exception, it runs the exception code. Let’s now rewrite our square_root function, but this time catch any exceptions raised. In the example, we try to execute x to the power of 0.5. Using except, in the case of an exception, we print x must be an int or float. We see that the resulting function works well for ints and floats and prints out what we wanted it to for a string.

Catching TypeError with a message. Image by Author
Catching TypeError with a message. Image by Author

We may also wish only to catch TypeError and let other errors pass through, in which case we would use except TypeError. Many different types of exceptions can be detected, and you can have a look at them in the Python documentation available online. Instead of slightly printing an error message, you will want to raise an error by using the keyword raise.

Raising ValueError with conditions. Image by Author
Raising ValueError with conditions. Image by Author

For example, the square_root function does something we may not want when applied to negative numbers. It returns a complex number that we may not want. Let’s say that we don’t wish our function to work for negative numbers. Using an if clause, we can raise a ValueError for cases in which the user passes the function a negative number. If we give our new function a negative number, see it returns the prescribed ValueError.


Other Interesting Articles
#1 Function Arguments: Default, Keyword, and Arbitrary
#2 Scope of Variable and LEGB Rule
#3 Writing Your Own Functions
#4 Python: Procedural or Object-Oriented Programming?
#5 Data Science with Python: How to Use NumPy Library
#6 Do you have the Software Engineer and Data Scientist skills?

About the Author

Wie Kiang is a researcher who is responsible for collecting, organizing, and analyzing opinions and data to solve problems, explore issues, and predict trends.

He is working in almost every sector of Machine Learning and Deep Learning. He is carrying out experiments and investigations in a range of areas, including Convolutional Neural Networks, Natural Language Processing, and Recurrent Neural Networks.

Connect on LinkedIn


Related Articles