Creating a list where a certain char occur a set number of times
<p>I am creating a list in python 2.7
The list consists of 1's and 0's however I need the 1's to appear randomly in the list and a set amount of times.</p>

<p>Here is a way I found of doing this however can take a long time to create the list</p>

<pre><code>numcor = 0




while numcor != (wordlen):    #wordlen being the set amount of times
    usewrong = []

    for l in list(mymap):

        if l == "L": #L is my map an telling how long the list needs to be
            use = random.choice((True, False))
            if use == True:
                usewrong.append(0)
            else:
                usewrong.append(1)
                numcor = numcor + 1
</code></pre>

<p>Is there a more effiecient way of doing this?</p>

<p>Here is a different approach:</p>

<pre><code>from random import *
# create a list full of 0's
ls = [0 for _ in range(10)]
# pick e.g. 3 non-duplicate random indexes in range(len(ls))
random_indexes = sample(range(len(ls)), 3)
# create in-place our random list which contains 3 1's in random indexes
ls = [1 if (i in random_indexes) else ls[i] for i,j in enumerate(ls)]
</code></pre>

<p>The output will be:</p>

<pre><code>&gt;&gt;&gt; ls
[0, 1, 0, 1, 0, 0, 0, 0, 1, 0]
</code></pre>

python arrays list python-2.7