Tashaho Tashaho - 1 month ago 10
Python Question

Create Python list of list with random numbers and lengths

How to create create a list of lists with random numbers in Python? The length of the list and the sub-lists will be random too.I tried this.

import random
p= []
for a in range(random.randint(5,7)):
p.append(random.randint(1,20))
k=[]
for b in range(random.randint(4,8)):
k.append(p)
print k


why it did not work?

Answer Source

You can use random.sample provided your range is larger than the number of random variables you select from it. This approach ensures each random value in the nest list is unique:

from random import randint
import random

number_of_lists = randint(0,1000)

random_data = []
for number in xrange(0,number_of_lists):    
    list_length=randint(0,1000)
    random_data.append(random.sample(range(1, 100000), list_length))