Shuffle a list within a specific python range

I am very new to Python, so bear with me. I would like to run a program that will shuffle a string of integers in a specific range, but without having to enter every integer within that range. Ie, I want to randomize the list of integers b / w 1-100 without input (1, 2, 3 ... 100).

Yes, I looked at other answers to similar questions, but everyone asks for a single integer in a certain range or is not responsible for Python or asks for something more complex. Thanks

+4
source share
2 answers

You can use range() to create a list of integers, and then apply random.shuffle() on that list.

 In [141]: lis = range(1,11) In [142]: lis Out[142]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [143]: random.shuffle(lis) In [144]: lis Out[144]: [1, 4, 3, 10, 8, 2, 6, 9, 5, 7] 

help() on range() :

range ([start,] stop [, step]) β†’ list of integers

Returns a list containing the arithmetic progression of integers. range (i, j) returns [i, i + 1, i + 2, ..., j-1]; start (!) by default is 0. When a step is specified, it indicates an increase (or decrement). For example, range (4) returns [0, 1, 2, 3]. End point omitted! These are exactly valid indexes for a list of 4 items.

+11
source

If you want the entire population within a given range, as suggested by @Ashwini, you can use random.shuffle

In case you are interested in a subset of the population, you can count on using random.sample

 >>> random.sample(range(1,10),5) [3, 5, 2, 6, 7] 

You can also use this to simulate random.shuffle

 >>> random.sample(range(1,10),(10 - 1)) [4, 5, 9, 3, 2, 8, 6, 1, 7] 

Note The advantage of using random.sample over random.shuffle is that it can work on iterators, so in

  • Python 3.X you don't need to convert range() to list
  • In Python 2, X you can use xrange
  • The same code can work in Python 2.X and 3.X
+5
source

All Articles