Double for loop in Python3
<p>There is list named L.
Which contains others list: L=[A,B,C,...N]
I want to for-loop, where B is no equal A (see #2)
Something like: for B is not A in L:</p>

<pre><code>for A in L: #1
    for B in L: #2
</code></pre>

<p>How can I do that?</p>

<p>Better solution using <code>itertools</code>, either <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="nofollow">with <code>permutations</code></a> or <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">with <code>combinations</code></a>:</p>

<pre><code>import itertools

# If it's okay to see L[1], L[2], and later L[2], L[1], that is, order sensitive,
# matching your original question's specification of only avoiding pairing with self:
for A, B in itertools.permutations(L, 2):
    ...

# If you only want to see L[x] paired with L[y] where y &gt; x,
# equivalent to results of Daniel Sanchez's answer:
for A, B in itertools.combinations(L, 2):
    ...
</code></pre>

<p>Either one of these is significantly faster than using nested loops that require indexing (and bonus, requires only one level of indentation, reducing "arrow patterns" in your code).</p>

<p>If the body of the loop was <code>print(A, B, sep=',', end=' ')</code> and <code>L = [1, 2, 3]</code>, the output of the <code>permutations</code> loop would be:</p>

<pre><code>1,2 1,3 2,1 2,3 3,1 3,2
</code></pre>

<p>For <code>combinations</code>, you'd get:</p>

<pre><code>1,2 1,3 2,3
</code></pre>

<p>so choose whichever matches your desired behavior.</p>

<p>An additional benefit of using the <code>itertools</code> functions is that they'll work just fine when <code>L</code> is a non-sequence collection (e.g. a <code>set</code>), or when it's an iterator that can only be traversed once (they'll cache the values internally so they can produce them more than once). Other solutions require explicit conversion to <code>list</code>/<code>tuple</code> or the like to handle the "<code>L</code> is a one-use iterator" case.</p>

python python-3.x permutation