Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you are attempting to do in this code is not what you think (i suspect) for instance:<br> <code>x[::2]</code> will return a slice containing every <code>odd</code> element of x, since x is of size 20,<br> the slice will be of size 10, but you are trying to assign a non-iterable of size 1 to it.</p> <p>to successfully use the code you have you will need to do:</p> <pre><code>x = [True]*20 x[::2] = [False]*10 </code></pre> <p>wich will assign an iterable of size 10 to a slice of size 10.</p> <p>Why work in the dark with the number of elements? use </p> <pre><code>len(x[::2]) </code></pre> <p>which would be equal to 10, and then use </p> <pre><code>x[::2] = [False]*len(x[::2]) </code></pre> <p>you could also do something like:</p> <pre><code>x = [True if (index &amp; 0x1 == 0) else False for index, element in enumerate(x)] </code></pre> <hr> <p>EDIT: Due to OP edit</p> <p>The <a href="http://docs.python.org/library/itertools.html#itertools.cycle" rel="nofollow">documentation</a> on cycle says it <code>Repeats indefinitely.</code> which means it will continuously 'cycle' through the iterator it has been given.</p> <p>Repeat has a similar implementation, however <a href="http://docs.python.org/library/itertools.html#itertools.repeat" rel="nofollow">documentation</a> states that it<br> <code>Runs indefinitely unless the times argument is specified.</code><br> which has not been done in the questions code. Thus both will lead to infinite loops.</p> <p>About the <code>itertools</code> being faster comment. Yes itertools are generally faster than other implementations because they are optimised to be as fast as the creators could make them.</p> <p>However if you do not want to recreate a list you can use <code>generator expressions</code> such as the following:</p> <pre><code>x = (True if (index &amp; 0x1 == 0) else False for index, element in enumerate(x)) </code></pre> <p>which do not store all of their elements in memory but produce them as they are needed, however, generator functions can be used up.</p> <p>for instance:</p> <pre><code>x = [True]*20 print(x) y = (True if (index &amp; 0x1 == 0) else False for index, element in enumerate(x)) print ([a for a in y]) print ([a for a in y]) </code></pre> <p>will print <code>x</code> then the elements in the generator <code>y</code>, then a null list, because the generator has been used up.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload