Search code examples
pythonlistenumerate

List Enumeration in Python


The snippet below is from a code tracing exercise.

import copy

def ct1(A, B, C, D, E):
    result = [ ]
    # 0 1 2 3 4 5 6 7 8 9
    pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
    for i,pair in enumerate(pairs):
        (L, M) = pair
        if (L is M): result.append(i)
        elif (L == M): result.append(10*i)

    return result
def f(L):
    L[0] += 1
    return L

A = list(range(3))
B = copy.copy(A)
C, D, E = A, B+[ ], f(B)
print(ct1(A, B, C, D, E))

The part I'm confused about is the enumeration used in the for loop. From the documentation for enumerate() it looks like pair should had have values like:

(0, ([0, 1, 2], [1, 1, 2]))
(1, ([0, 1, 2], [0, 1, 2]))
(2, ([0, 1, 2], [0, 1, 2]))
(3, ([0, 1, 2], [1, 1, 2]))
(4, ([1, 1, 2], [0, 1, 2]))
(5, ([1, 1, 2], [0, 1, 2]))
(6, ([1, 1, 2], [1, 1, 2]))
(7, ([0, 1, 2], [0, 1, 2]))

during the iteration, which means 'L' should have values from 0 through 7 and 'M', the tuples ([0, 1, 2], [1, 1, 2]) through ([0, 1, 2], [0, 1, 2]). However when I run this code through the debugger, I see both L and M are lists instead. For example, when i = 0, L = [0, 1, 2] and M = [1, 1, 2] and so forth. Can someone please explain what is going on?


Solution

  • Of course L and M are lists. If you run

    pairs = [(A,B),(A,C),(A,D),(A,E),(B,C),(B,D),(B,E),(C,D),(C,E),(D,E)]
    for i, pair in enumerate(pairs):
        print(i, pair)
    

    you will get the desired result. So the tuple you are looking for is saved in pairs. With the line

    # ...
    (L, M) = pair
    # ...
    

    you split up the tuple referenced by pair into its elements, which are – in the first iteration – the two lists referenced by A and B.

    The above line essentially means

    (L, M) = (A, B)
    

    which is equivalent to

    L, M = A, B
    

    which in turn means "assign A to L and assign B to M".