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:

def square(a):
    return a*a

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:

#create a list of lengths from a list of given names.
def myfunc(a):
  return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
#convert the map into a list, for readability:
#[5, 6, 6]

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).

# define two lists of numbers
evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Perform a mapping square for evens
evenSquared = list(map(lambda e: e**2, evens))
#[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

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.

evenSquared = list(map(lambda e: e**2, filter(lambda e: e > 4 and e < 16, evens)))
#[36, 64, 100, 144, 196]

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
# Limit the items operated on with a predicate condition
oddSquared = [e ** 2 for e in odds if e > 3 and e < 17]
#[36, 64, 100, 144, 196]

Set comprehension

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

# define a list of temperature data points
ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29]
# build a set of unique Fahrenheit temperatures
ftemps1 = [(t * 9/5) + 32 for t in ctemps]
ftemps2 = {(t * 9/5) + 32 for t in ctemps}
#[41.0, 50.0, 53.6, 57.2, 50.0, 73.4, 105.8, 86.0, 53.6, 75.2, 53.6, 64.4, 84.2]
#{64.4, 73.4, 41.0, 105.8, 75.2, 50.0, 84.2, 53.6, 86.0, 57.2}

We can also apply to characters in a String.

# build a set from an input source
sTemp = "The quick brown fox jumped over the lazy dog"
chars = {c.upper() for c in sTemp if not c.isspace()}
#{'B', 'U', 'P', 'V', 'Q', ..., 'F', 'R', 'O', 'X', 'L', 'C'}

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.

# Merge two dictionaries with a comprehension
team1 = {"Jones": 24, "Jameson": 18, "Smith": 58, "Burns": 7}
team2 = {"White": 12, "Macke": 88, "Perce": 4}
newTeam = {k: v for team in (team1, team2) for k, v in team.items()}
#{'Jones': 24, 'Jameson': 18, 'Smith': 58, 'Burns': 7, 'White': 12, 'Macke': 88, 'Perce': 4}

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.