List Comprehension are good, but they are not suitable for all the scenarios. In your case, writing an explicit for
loop makes more sense.
However, you may use random.shuffle
in order to get the similar result more efficiently. If you need both 0
and 1
to be 20 in count in the resultant list, you can do:
>>> import random
>>> my_list = [0]*20 + [1]*20
>>> random.shuffle(my_list)
>>> my_list
[0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0]
However if you want the count of 0
to be random between 0-20 (which your current code is doing), then you may modify the above logic a little like:
>>> zero_count = random.randint(0, 20)
>>> one_count = 40 - zero_count
>>> my_list = [0]*zero_count + [1]*one_count
>>> random.shuffle(my_list)
>>> my_list
[1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1]