How to generate a list of random numbers in Python?
In Python, you can use the random module to generate a list of random numbers. Here are some example codes:
- Create a list containing n random integers.
import random
n = 5
random_nums = [random.randint(1, 10) for _ in range(n)]
print(random_nums)
- Generate a list of n random floating point numbers.
import random
n = 5
random_nums = [random.uniform(1.0, 10.0) for _ in range(n)]
print(random_nums)
- Create a randomized list.
import random
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)
Here are some methods for generating random number lists. You can choose the method that best fits your needs.