简体   繁体   中英

differences in for loops in python

can someone explain why these two loops look like they do the same thing, when in fact the second version doesn't find the duplicate number correctly?

list1 = [1,2,13,4,6,6,8,11,10]

for i in range(len(list1)):
    for j in range(i+1, len(list1)):
            if list1[i] == list1[j]:
                print i, j
                print True
            else:
                print False
print "--------------------------------------"

for i in list1:
    for j in list1:
        if i == j + 1:
            print True, i, j
        else:
            print False

They don't do the same thing at all. The second one loops through the whole of list1 in the inner loop, instead of just from the current index onwards. And, for some reason, you add 1 to the value before comparing, so it wouldn't be equal.

for i in range(len(list1)):
    for j in range(i+1, len(list1)):
            if list1[i] == list1[j]:
                print i, j
                print True
            else:
                print False

The code above iterates over a list which is generated by the range() function which returns a list of numbers that in your case is [0,1,2,....,len(list1) - 1] in the first loop.
In the second loop the list that you go over is [i + 1, i + 2, i + 3,...,len(list1) - 1] .
On every iteration i and j are assigned to one item of the list just like a normal for loop (Java, C#, C++ and more).


for i in list1:
    for j in list1:
        if i == j + 1:
            print True, i, j
        else:
            print False

In this code i and j are assigned to each item value in list1 .
On every iteration i and j will be assigned to the next item value in the list, NOT THE POSITION .
In your case i value will be 1 then 2 then 13 ... Same applies to j .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM