Ranges and random

Here are som more expressions, of a more unusual form but very useful and well used in Python.

Range

Ranges are mostly used to control loops and in list comprehensions in Python, but you can also transform them into lists. The Python documentation describes them in ranges.

# range of numbers 0 ... 9. 

range(10)
range(0, 10)
# the list funtion turns the range into a list, 
# so you can see the values in the range.

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# you can also indicate  with what number to start the range.

list(range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]
# and you can say with what step to go from one number to the next

# start with 0, end at 9 and use a step of 2:
list(range(0,10,2))
[0, 2, 4, 6, 8]

Random

Random numbers and random values of other types are very useful. For example, to test our programs with random data when we explore how efficient programs are. There are a number of functions for generating random values and the Python documentation describes the ones we will use most often in functions for integers, functions for sequences and real-valued distributions.

In order to use all the functions we illustrate here you need to import the library random:

import random

Random integer numbers

import random
# a random number that can be 0 or 1 or 2 or ... or 9. 
random.randrange(10)
6
# a random number that can be 2 or 3 or ... or 9

random.randrange(2,10)
4
# simulate throwing a dice:

random.randrange(1,7)
3
# combine list comprehension and random numbers to
# simulate throwing 5 dices:

[random.randrange(1,7) for x in range(5)]
[2, 4, 6, 6, 3]
# 10 experiments throwing 5 dices 
# The value of this expression is a list of 10 lists with 5 elements each!

[[random.randrange(1,7) for x in range(5)] for y in range(10)]
[[5, 2, 5, 1, 4],
 [4, 1, 1, 5, 2],
 [1, 2, 5, 2, 2],
 [6, 2, 4, 6, 2],
 [4, 2, 4, 4, 2],
 [4, 2, 1, 2, 1],
 [1, 2, 2, 5, 6],
 [1, 5, 4, 3, 6],
 [3, 1, 5, 1, 1],
 [6, 4, 3, 2, 1]]

Functions for sequences

Sequences can be strings, lists or ranges.

# a random letter from the alphabet:

random.choice('abcdefghijklmnopqrstuvwxyz')
'o'
# a random even number in the range 0 ... 999999:

random.choice(range(0,1000000,2))
326082

Floating point numbers

There are many interesting functions to generate numbers according to very specific distributions. We will only use one (maybe): a number in the interval \([0,1)\)

random.random()
0.8416593349315945