14

I'm 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 input each integer within that range. I.e., I want to randomize the list of integers from 1 to 100 without typing out (1, 2, 3...100).

Yes, I've looked at other answers to similar questions, but all are asking for one integer within a specific range, or are not answered for Python, or are asking for something way more complex. Thanks

Adam Smooch
  • 1,167
  • 1
  • 12
  • 27
common_currency
  • 141
  • 1
  • 1
  • 5

2 Answers2

17

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

>>> lst = list(range(1,11))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> random.shuffle(lst)
>>> lst
[4, 5, 3, 9, 2, 10, 7, 1, 6, 8]

Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
10

In case you want the entire population within a given range, As @Ashwini proposed you can use random.shuffle

In Case you are interested in a subset of the population, you can look forward to use random.sample

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

You may 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 , 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
  • Same Code can work in Python 2.X and 3.X
Abhijit
  • 62,056
  • 18
  • 131
  • 204