Nested for Loop optimization in python
<p>i want to optimize 2 for loops into single for loop, is there any way as length of array is very large.</p>

<pre><code>A = [1,4,2 6,9,10,80] #length of list is very large
B  = []
for x in A:
    for y in A:
        if x != y:
            B.append(abs(x-y))
print(B)
</code></pre>

<p>not any better but more pythonic:</p>

<pre><code>B = [abs(x-y) for x in A for y in A if x!=y]
</code></pre>

<p>unless you absolutely need duplicates (<code>abs(a-b) == abs(b-a)</code>), you can half your list (and thus computation):</p>

<pre><code>B = [abs(A[i]-A[j]) for i in range(len(A)) for j in range(i+1, len(A))]
</code></pre>

<p>finaly you can use the power of <code>numpy</code> to get C++ speedup:</p>

<pre><code>import numpy as np

A = np.array(A)
A.shape = -1,1 # make it a column vector

diff = np.abs(A - A.T) # diff is the matrix of abs differences

# grab upper triangle of order 1 (i.e. less the diagonal)
B = diff[np.triu_indices(len(A), k=1)]
</code></pre>

<p>But this will always be O(n^2) no matter what...</p>

python loops optimization