How to create a list of tuples with random numbers in python ?


To create a list of tuples with random numbers in python a solution is to use the list comprehensions and random module, example:

>>> import random
>>> l = [(random.randrange(0, 50), random.randrange(0, 20)) for i in range(10)]
>>> l
[(22, 17), (7, 19), (2, 12), (37, 14), (7, 17), (34, 9), (16, 17), (25, 10), (3, 2), (38, 5)]

to generate random float, a solution is to use uniform(a,b):

>>> l = [(random.uniform(0.0, 1.0), random.uniform(0.0, 1.0)) for i in range(10)]
>>> l
[(0.4014888720054153, 0.564237129581307), (0.37839753881672955, 0.958916279333259), (0.17355922012211167, 0.48518511610860104), (0.5830386633170813, 0.07710311150724536), (0.9531671161016905, 0.4543647439446762), (0.5718747704610297, 0.19444668674655952), (0.07240780334130892, 0.2330138323117349), (0.8470072240773081, 0.12791563123856586), (0.8753803608034938, 0.9818640656070039), (0.7022939797812323, 0.9903516574270013)]

References