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
The random. shuffle() function makes it easy to shuffle a list's items in Python. Because the function works in-place, we do not need to reassign the list to itself, but it allows us to easily randomize list elements.
To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.
Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.
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).
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
range()
to listxrange
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With