How do I generate a list of length N with random 0 and 1 values , but with a given number of 1\'s put randomly in the list.
For example, I want a list of 10
I like the shuffle() approach in the other answers; however, there is another way that uses fewer calls to the random number generator. Start with a list of zeros. Then use sample() to pick the 7 indicies that should be set to ones:
>>> from random import sample
>>> result = [0] * 10
>>> for i in sample(range(10), k=7):
result[i] = 1
>>> result
[1, 0, 1, 1, 0, 1, 1, 1, 1, 0]