Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want the effect of a nested for loop, use:</p> <pre><code>import itertools for i, j in itertools.product(range(x), range(y)): # Stuff... </code></pre> <p>If you just want to loop simultaneously, use:</p> <pre><code>for i, j in zip(range(x), range(y)): # Stuff... </code></pre> <p>Note that if <code>x</code> and <code>y</code> are not the same length, <code>zip</code> will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use <code>itertools.zip_longest</code>.</p> <p><strong>UPDATE</strong></p> <p>Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants <code>zip</code> <em>or</em> <code>product</code>. I think they want a <code>set</code>:</p> <pre><code>def equal_elements(t1, t2): return list(set(t1).intersection(set(t2))) # You could also do # return list(set(t1) &amp; set(t2)) </code></pre> <p>The <code>intersection</code> method of a <code>set</code> will return all the elements common to it and another set (Note that if your lists contains other <code>list</code>s, you might want to convert the inner <code>list</code>s to <code>tuples</code> first so that they are hashable; otherwise the call to <code>set</code> will fail.). The <code>list</code> function then turns the set back into a list.</p> <p><strong>UPDATE 2</strong></p> <p>OR, the OP might want elements that are identical in <em>the same position in the lists</em>. In this case, <code>zip</code> would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:</p> <pre><code>def equal_elements(t1, t2): return [x for x, y in zip(t1, t2) if x == y] </code></pre> <p>This will return a list containing only the elements that are the same and in the same position in the lists.</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