Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating lists of random length in python

I am writing a program in python. In it, I want to generate a list. This list will start at one and increment by one [1, 2, 3, 4, 5, etc.].

However, I want the length of the list to be random, between 3 numbers and 8 numbers long. For example, on one run the list might generate [1, 2, 3, 4], on another it might generate 1, 2, 3, 4, 5, 6], another run might generate [1, 2, 3], and so on.

I know how to make a list generate random numbers but not so that it increments numbers at a random length. Thank you for your time. I am using Python 2.7 by the way.

like image 290
user163505 Avatar asked Mar 20 '26 17:03

user163505


2 Answers

Just

l1 = [ i + 1 for i in range(randint(...)  ]
like image 119
Christian Tapia Avatar answered Mar 22 '26 06:03

Christian Tapia


import random
start = 1
end = random.randint(3, 8)
l = range(start, end + 1)
like image 43
Ant Avatar answered Mar 22 '26 05:03

Ant