user2829468
user2829468

Reputation: 105

How to make a random array in Python?

Sorry for the noob question.. But I can't seem to figure out how to make an array with a random set of values.

My goal is to make an array with a set of 10 random numbers (like [10, 2, 45, 22, 31, 22, 12, 88, 90, 6]) Does anyone know how I can do this in python?

Upvotes: 1

Views: 12496

Answers (4)

Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10734

The solutions mentioned are good. As a new way if you wanted to use shuffle, This code generates a shuffled list of numbers from 1 to 100 and selects the first 10:

import random

# Create an array of numbers from 1 to 100
arr = list(range(1, 101))

# Shuffle the array randomly
random.shuffle(arr)

# Select the first 10 numbers from the shuffled array
random_10_numbers = arr[:10]

print(random_10_numbers)

Upvotes: 0

JeffCharter
JeffCharter

Reputation: 1549

If you want the simple answer that works correctly:

import random
random.choices(range(5), k=8)

Upvotes: 0

ness
ness

Reputation: 41

Here is how you can create the array

import random

ar=random.sample(range(100),20)

Upvotes: 4

TerryA
TerryA

Reputation: 60024

Using the random module:

>>> import random
>>> L = range(100)
>>> amount = 10
>>> [random.choice(L) for _ in range(amount)]
[31, 91, 52, 18, 92, 17, 70, 97, 17, 56]

Upvotes: 5

Related Questions