A.I, Data and Software Engineering

Advanced python: comprehension


In this article, we’ll learn about a Python language construct known as comprehensions for creating a new sequence based on existing one but its syntax is more human-readable than lambda functions. These can be applied to lists, sets, and dictionaries. 

REVIEW Lambda and map

Lambda is an anonymous function (function without name). Let have a quick look at the following example for its syntax:

We can rewrite the above function as:

Lambda Functions In Python (Anonymous Functions) | FACE Prep
Lambda syntax to square a number (a is the argument name)

Now, recall the map function over a list. It takes a function as a parameter and applies to each member of a list of values. The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter. For example:

List Comprehension with filter

Firstly, let’s use the map to create a list of numbers that are squares of the original numbers in the list using lambda (small anonymous function).

Now, we want to apply the square function to numbers that are greater than 4 and less than 16. We can modify the mapping function as follow.

List comprehensions are usually more human-readable than lambda functions. It is easier to understand what the programmer was trying to accomplish when using list comprehensions.

list comprehension
List comprehension example for squaring a list with a filter

Set comprehension

In the following example, we converted temperatures from one scale to another using this kind of approach.

We can also apply to characters in a String.

Dictionary comprehensions

With the same technique, handling dictionary with comprehension is rather easy and convenient. We can populate a new dictionary with inline key and value arguments.

In the following example, we have two teams of members (keys) and their scores (values). Now, we will create a new dictionary by merging the two teams using comprehension.

You can read more about advanced python from these articles.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest


You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.