user163505
user163505

Reputation: 499

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.

Upvotes: 2

Views: 9258

Answers (6)

John Damen
John Damen

Reputation: 409

you can do it using range() where the first argument is the start and the second argument is the random length

import random
range(1, random.randint(3, 8))

Upvotes: 2

lennon310
lennon310

Reputation: 12689

from random import randint  
l = range(1,randint(3,8)+1 )
print l

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142146

An itertools approach - which also means if you don't need to materialise the list, then you don't have to:

from itertools import count, islice
from random import randint

mylist = list(islice(count(1), randint(3, 8)))

Since count is a generator incrementing by 1 each time, we use islice to "limit" the total number of items we take from it, and then build a list.

Upvotes: 2

RyPeck
RyPeck

Reputation: 8147

If you specify 4 at the bottom end and 9 as the top of randint you'll get up to 8 numbers like you ask for. You need to do this because you start the range at 1.

>>> import random
>>> range(1, random.randint(4,4))
[1, 2, 3]
>>> range(1, random.randint(9,9))
[1, 2, 3, 4, 5, 6, 7, 8]
>>> rand_list = range(1, random.randint(4,9))
>>> rand_list
[1, 2, 3, 4, 5, 6, 7]

Range() first argument is the starting point. The 2nd argument is the stop. Many of the other answers will sometimes return only two numbers, in the cases where stop == 3.

>>> range(1,3)
[1, 2]
>>> range(1,4)
[1, 2, 3]
>>> range(1,8)
[1, 2, 3, 4, 5, 6, 7]
>>> range(1,9)
[1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

Ant
Ant

Reputation: 5414

import random
start = 1
end = random.randint(3, 8)
l = range(start, end + 1)

Upvotes: 4

Christian Tapia
Christian Tapia

Reputation: 34146

Just

l1 = [ i + 1 for i in range(randint(...)  ]

Upvotes: 5

Related Questions