jpcgandre
jpcgandre

Reputation: 1505

generate random -1 or 1 values in a single line of code

I'd like to generate random values equal to -1 or 1. I can do that by generating random integer values 0 or 1 times 2 and minus 1, but maybe there is a more simple way of doing this?

Upvotes: 2

Views: 272

Answers (2)

glglgl
glglgl

Reputation: 91149

import random
print 1 if random.random() >= 0.5 else -1

Upvotes: 3

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

How about?

random.choice([-1, 1])

Example -

>>> from random import choice
>>> choice([-1, 1])
1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
1

Upvotes: 10

Related Questions