Surprising behaviour of enumerate function
<p>I wrote some Python code using the enumerate function. </p>

<pre><code>A = [2,3,5,7]

for i, x in enumerate(A):
    # calculate product with each element to the right
    for j, y in enumerate(A, start=i+1):
        print(x*y)
</code></pre>

<p>I expected it to calculate 6 products: 2*3, 2*5, 2*7, 3*5, 3*7, 5*7</p>

<p>Instead, it calculated all possible 16 products. What's going on?</p>

<p>The question here is firstly what enumerate did, and secondly why you're using it. The base function of enumerate is to convert an iterable of the form <code>(a,b,c)</code> to an iterable of the form <code>((start,a), (start+1,b), (start+2,c))</code>. It adds a new column which is typically used as an index; in your code, this is <code>i</code> and <code>j</code>. It doesn't change the entries contained in the sequence. </p>

<p>I believe the operation you were intending is a slice, extracting only part of the list:</p>

<pre><code>for i, x in enumerate(A):
  for y in A[i+1:]:
    print(x*y)
</code></pre>

<p>If it is important not to copy the list (it rarely is), you can replace <code>A[i+1:]</code> with <code>itertools.islice(A, i+1, len(A))</code>. </p>

<p>A side note is that the <code>start</code> argument may be useful in the outer loop in this code. We're only using <code>i+1</code>, not <code>i</code> so we may as well use that value as our index:</p>

<pre><code>for nextindex, x in enumerate(A, 1):
  for y in A[nextindex:]:
    print(x*y)
</code></pre>

python