1

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?

1
  • 1
    What you call an "array" is going to be a "list" in Python 99% of the time. For actual arrays, use the array module. Commented Sep 29, 2013 at 23:56

4 Answers 4

6

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Take note that random.sample() will reduce the list you pass it, meaning it will never make duplicates. This might be what you want, but for "more" random lists use: [random.randint(min,max) for _ in xrange(len_you_want)].
FYI, This will not repeat any values, i.e., it samples without replacement, so the example given by @user2829468 is not a possible outcome, since it has 22 twice.
Thank you, this answered my question perfectly ^_^!
4

Here is how you can create the array

import random

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

1 Comment

this is for 0 to 99
0

If you want the simple answer that works correctly:

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.