简体   繁体   中英

To find duplicates in a python list, why doesn't this logic work?

While I am aware that the best and simplest method to find duplicates in a list is by using Collections.Counter, I wish to know where does the following logic fail.

def uniquenumbercheck(listarg):
    for i in range(2,len(listarg)):
        for j in range(1,i-1):
            if(listarg[i]==listarg[j]):
                print("duplicate value appeared : "+str(listarg[i]))
                return
    print("all entered values are unique. ")

The program is running but failed to display the correct output.Could not figure out the mistake.For the example input of 1,1,0 integers to list, it says that they are unique.

Off-by-one error. In Python, indexes start at 0 , not 1 . So,

for i in range(2, len(listarg)):
    for j in range(1, i - 1):

should be:

for i in range(1, len(listarg)):
    for j in range(0, i):

Also, range(1, len(listarg)) can also be written as range(len(listarg)) .

i am assuming you are searching for duplicates within a list:

myl = [1, 2, 3, 5, 6, 1, 2]

for i in myl:
    if myl.count(i) > 1:
        print i

where the duplicates are printed out.

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