leonardik
leonardik

Reputation: 131

Random list only with -1 and 1

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

Answers (8)

LeopardShark
LeopardShark

Reputation: 4446

[random.choice((-1, 1)) for _ in range(10)]

random.choice() selects a random element from a sequence.

Upvotes: 2

Moez Ben Rebah
Moez Ben Rebah

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

drsealks
drsealks

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 1s than -1s. 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

Peter O.
Peter O.

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

rossum
rossum

Reputation: 15693

An alternative method:

  1. Generate a 10 bit random number in 0..1023.

  2. Express the number as a binary text string, making sure to include all leading zeros.

  3. Read the string, outputting "-1" for every zero and "1" for every one.

Upvotes: 0

yatu
yatu

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

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

import random
for x in range(10): 
    print (random.choice([-1,1]))

Upvotes: 2

NPE
NPE

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

Related Questions