2

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.

1
  • range(1,random.randint(4,9)) Commented Nov 16, 2013 at 18:12

6 Answers 6

5

Just

l1 = [ i + 1 for i in range(randint(...)  ]
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

You want random.randint(3, 9) there.
This at times will generate only two numbers.
Thanks for pointing out :-) hope this minor problems can be solved by the op himself (though i have corrected my answer)
probably better will be range(start, start+end)
2

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.

Comments

2

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))

Comments

0

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]

1 Comment

Why isn't my answer useful?
0
from random import randint  
l = range(1,randint(3,8)+1 )
print l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.