How to Generate Random Data in Python
Published on Aug. 22, 2023, 12:16 p.m.
To generate random data in Python, you can use the built-in random
module. It provides various functions to generate random numbers, texts, and sequences. Here are some examples:
- Generate random integers:
import random
Generate a random integer between 0 and 9
random_int = random.randint(0, 9)
print(random_int)
2. Generate random floats:
import random
Generate a random float between 0 and 1
random_float = random.random()
print(random_float)
3. Generate random strings:
import random
import string
Generate a random string of length 10
random_string = ‘’.join(random.choices(string.ascii_uppercase + string.digits, k=10))
print(random_string)
4. Shuffle a list:
import random
my_list = [1, 2, 3, 4, 5]
Shuffle the list in-place
random.shuffle(my_list)
print(my_list)
The `random` module also provides many other functions, such as `choice()`, `sample()`, `randrange()`, and `uniform()`, that can be used to generate random data for various use cases.