We give an introduction to list comprehensions and NumPy arrays.

List Comprehensions

List comprehentions give us a new way to create lists that is reminiscent of set builder notation. For example, suppose we wanted to create a list containing the positive squares from 1 to 100. That is, we want [1,4,9,...,100]. This can be done using a list, a for loop, and the append method.

This same task can be accomplished using the += operator, which serves as concatenation here. Note that we must have brackets around i**2 for this to work.

A list comprehension allows us to create the same list in a compact and easy-to-read way that is similar to the notation .

The general syntax for a list comprehension has the following form:

==============================
 
[expression(var) for var in iterable if condition]  
==============================

The term expression is some function or expression that is computed using each value of var as it iterates over iterable (usually a list or iterable created using the range function). In order to filter results, one can add an optional comparison at the end of the list comprehension, represented by the condition term.

The above list comprehension format generates a list that is equivalent to myList (below) after running the following chunk of code:

==============================
 
myList = []  
for var in iterable:  
        if condition:  
         myList += [expression(var)]  
==============================

The list comprehension below gives all of the nonnegative even cubes that are at most 1000.

We will use list comprehensions to generate lists containing desired elements without resorting to using a loop. The use of list comprehensions is intended to increase the readibility of the code.

NumPy Arrays

The NumPy library is a scientific computing library often used by data scientists. We will dive deepter into the contents of this library in a later section. For now, we are interseted in a new type of object that is provided by this library: an array. Arrays are like lists with additional functionality designed for handling large data sets.

In the next section, we will use arrays together with the Matplotlib library to create graphs. So, for now, our use of arrays will be limited to some basic functions.

The example above showcases our main use of arrays in the next section. When performing a mathematical operation on an array, that operation is performed on each individual entry in the array. These vectorized functions will allow us to create data sets to be plotted with significantly less work while increasing code readibility.

The line import numpy as np (which needs to appear only once in a notebook) tells our notebook that we want to have access to the NumPy library. The term np is a commonly used alias for NumPy. To call any NumPy function, we must first write np. followed by the function name. This is to ensure that there is no ambiguity between a built-in Python function and a NumPy function of the same name.

Some commonly used NumPy functions include:

  • np.array - converts a list into an array
  • np.max - finds the maximum in an array
  • np.sort - sorts an array
  • np.cumsum - computes the cumulative sum of an array
  • np.random.randint - generates an array of random integers
  • np.exp,np.sin - the vectorized functions for and
  • np.pi - the constant
  • np.linspace - a quick way to create a desired number of sample points in an interval

Problems

Use a list comprehension to list the positive integers less than or equal to 20 that are divisible by either 3 or 5.
Use or to determine if a number is divisble by 3 or 5. Note that the second hint for this problem is the solution.
Use a list comprehension to compute the sum
Apply the sumfunction to a list comprehension.
Use a list comprehension or NumPy array to define a function in Python that returns the list of divisors of a positive integer .
Your function should only be one line long. It should return a list comprehension. Note that the second hint for this problem is the solution.
Use a list comprehension or NumPy array to define a function in Python that determines if an integer is prime or not. If the number is prime, the function should return the value True and False otherwise.
You should be able to use your answer to the previous problem by applying the len function. Note that the second hint for this problem is the solution.
Use a list comprehension or NumPy array to create a list containing the values for . Note that the hint for this problem is the solution.
A list comprehension solution:
A NumPy array solution:
Use a list comprehension to generate the set of all pairs .
Use a list comprehension with two variables and two for _ in _ statements. That is, write a list comprehension of list comprehensions without additional brackets. Note that the next hint for this problem is the solution.

Workspace