# Making a list of integers: range

### 5.40.4 Making a list of integers: range

The range command creates lists of equally spaced numbers. It can take one, two or three arguments.

With one argument:

- range takes one argument:
  n, a positive integer.
- range(n) returns the list [0,1,…,n−1].

#### Example.

Input:

range(5)

Output:

⎡ ⎣ | 0,1,2,3,4 | ⎤ ⎦

With two or three arguments:

- range takes two mandatory and one optional argument:
  - a and b, two real numbers with a<b (unless the third argument p is provided and negative).
  - Optionally, p, a nonzero real number used for the step size (by default 1).
    (If p<0, then a must be larger than b.)
- range(a,b ⟨ p ⟩) returns the list [a, a+p, …] up to, but not including, b.

#### Examples.

- Input:
  range(4,10)
  Output:

  ⎡ ⎣ | 4,5,6,7,8,9 | ⎤ ⎦

- Input:
  range(2.3,7.4)
  Output:

  ⎡ ⎣ | 2.3,3.3,4.3,5.3,6.3,7.3 | ⎤ ⎦

- Input:
  range(4,13,2)
  Output:

  ⎡ ⎣ | 4,6,8,10,12 | ⎤ ⎦

- Input:
  range(10,4,-1)
  Output:

  ⎡ ⎣ | 10,9,8,7,6,5 | ⎤ ⎦

You can use the range command to create a list of values f(k), where k is an integer satisfying a certain condition. (See Section 12.3.3 for the for loop used below.)

- You can list the values of an expression in a variable which goes over a range defined by range.
  Input:
  [k^2 + k for k in range(10)]
  Output:

  | ⎡ ⎣ | 0,2,6,12,20,30,42,56,72,90 | ⎤ ⎦

- You can list the values of an expression in a variable which goes over a range defined by range and which satisfies a given condition.
  Input:
  [k for k in range (4,10) if isprime(k)]
  (See Section 5.5.14 for isprime.)
  Output:

  | ⎡ ⎣ | 5,7 | ⎤ ⎦

  Input:
  [k^2 + k for k in range(1,10,2) if isprime(k)]
  Output:

  | ⎡ ⎣ | 12,30,56 | ⎤ ⎦