Home > Software engineering >  Why about the function enumerate am I not understanding?
Why about the function enumerate am I not understanding?

Time:02-11

I guess am not really sure what or why example number two doesn't sort like example 1.

numList = [4,5,7,2,3,100,43,543,34]

for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if numList[i1] < numList[i2]:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)


for i1,x1 in enumerate(numList):
    for i2,x2 in enumerate(numList):
        if x1 < x2:
            numList[i1],numList[i2] = numList[i2],numList[i1]
            print(numList)
        

Example 1 result: [2, 3, 4, 5, 7, 34, 43, 100, 543]
Example 2 result: [2, 3, 4, 5, 34, 43, 100, 7, 543]

CodePudding user response:

The swap changes the value of numList[i1] in the body of the inner loop; it does not change the value of x1 (which won't change until the next iteration of the outer loop).

(That is, x1 is a reference to the int value that was at numList[i1] at the time of the assignment, not a reference to the i1th slot of numList.)

  • Related