# Python : generate a list containing only 0 and 1

I want to assign random label (0 or 1) to a data set. How can I create a list containing only 0 and 1?

E.g.

y = [1,0,1,1,0,0,1,0]

+1 vote
by (157k points)

You can use functions of the Python module "random" to create a list of 0 and 1 only.

1. Using randint(a,b): You can provide a=0 and b=1 in this function to get only 0 or 1 in the list.
2. Using random(): It generates a random float value between 0 and 1. You can apply round() to the float value to get 0 or 1.
3. Using uniform(a,b): It generates a random float value between a and b. You can provide a=0 and b=1 in this function and apply round() to the float value to get 0 or 1.
Here are examples using these functions:
>>> import random
>>> sample_size=10
>>> labels = [random.randint(0,1) for _ in range(sample_size)]
>>> labels
[0, 0, 1, 1, 0, 1, 1, 1, 1, 1]

>>> labels =[round(random.random()) for _ in range(sample_size)]
>>> labels
[0, 0, 0, 0, 0, 1, 1, 1, 1, 0]

>>> labels =[round(random.uniform(0,1)) for _ in range(sample_size)]
>>> labels
[0, 0, 0, 1, 0, 0, 1, 1, 1, 0]