Previous Up Next

6.3.4  Creating a list of integers

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

Examples

range(5)
     

0,1,2,3,4
          
range(4,10)
     

4,5,6,7,8,9
          
range(2.3,7.4)
     

2.3,3.3,4.3,5.3,6.3,7.3
          
range(4,13,2)
     

4,6,8,10,12
          
range(10,4,-1)
     

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 25.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. For example:

[k^2+k for k in range(10)]
     

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. For example:

[k for k in range(4,10) if isprime(k)]
     

5,7
          

(See Section 7.1.14 for isprime.)

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

12,30,56
          

Previous Up Next