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))
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]
You could use random.choice()
:
>>> [random.choice([-1, 1]) for _ in range(10)]
[1, -1, 1, 1, -1, 1, -1, -1, -1, -1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With