Reputation: 131
I need to create random list which consists only of -1 and 1 like -1,1,1,-1,-1 (without zeros). My current coding adds 0 that doesn't suite me.
import random
for x in range(10):
print (random.randint(-1,1))
Upvotes: 7
Views: 872
Reputation: 4446
[random.choice((-1, 1)) for _ in range(10)]
random.choice()
selects a random element from a sequence.
Upvotes: 2
Reputation: 312
random.choice([value1, value2]), used to print one of the values within a list, example:
import random
num = random.choice([-1, 1])
print(num)
Upvotes: 2
Reputation: 2354
Just want to add that if you don't want -1
and 1
to be generated with the equal probabilities, and you do not want to install some math packages(such as numpy
), you could also use the following method: say, you want there be 3 times more 1
s than -1
s. Then the idea is that you generate a random number from 0
to 100
. If the number you generate is larger than 25
, append 1
, otherwise, append -1
.
This can be expressed in the following one liner:
import random
[1 if random.randint(0,100)>25 else -1 for _ in range(25)]
This is quite a generic approach and allows one to easily control their distribution without external dependencies.
Upvotes: 0
Reputation: 32888
The following answer incorporates Lee Daniel Crocker's comment. He should post an answer of his own, then I will delete this one:
[random.randint(0,1)*2-1 for i in range(10)]
Upvotes: 0
Reputation: 15693
An alternative method:
Generate a 10 bit random number in 0..1023.
Express the number as a binary text string, making sure to include all leading zeros.
Read the string, outputting "-1" for every zero and "1" for every one.
Upvotes: 0
Reputation: 88276
You can use random.choices
, which randomly selects k
elements from a given sequence, avoiding this way the need for any looping:
random.choices([-1,1], k=10)
#[-1, -1, 1, 1, 1, -1, -1, 1, -1, -1]
Upvotes: 13
Reputation: 4199
import random
for x in range(10):
print (random.choice([-1,1]))
Upvotes: 2
Reputation: 500663
You could use random.choice()
:
>>> [random.choice([-1, 1]) for _ in range(10)]
[1, -1, 1, 1, -1, 1, -1, -1, -1, -1]
Upvotes: 3