Home > OS >  Check duplicates python function not working. Why?
Check duplicates python function not working. Why?

Time:12-11

New to python and trying to write a function that checks for duplicates in a list and returns the duplicated value if any however my function doesn't seem to work as expected, please assist.

Here's what I've tried:

names = ['Thandi', 'Lebo', 'Oratile', 'James', 'James', 'Thabo']

def find_duplicates(names):
    for name in names:
      if names.count(name) > 1:
        return name
      else:
        return 'N/A'

print(find_duplicates(names))

This returns N/A meaning no duplicates were found but the list does have a duplicate. Where is the problem?

Please and Thank you.

CodePudding user response:

The first name, Thandi has no duplicates, and your code takes the else branch and returns N/A. Move that return to after the loop.

CodePudding user response:

the problem that your code is achieving a return statement in the first iteration of the for loop. although you should return N/A when only you have completed all of your iterations and you're sure that no duplicates exist. so you can use a continue statement for each iteration that has no duplicates till you finish all of your iterations.
this code will run as you hope

names = ['Thandi', 'Lebo', 'Oratile', 'James', 'James', 'Thabo']


def find_duplicates(names):
    for name in names:
        if names.count(name) > 1:
            return name
        else:
            continue
    return 'N/A'


print(find_duplicates(names))

it also worth mentioning that as long as we are doing nothing after the if condition in the for loop we can remove the else clause from the code like that and you'll also get a correct output.

names = ['Thandi', 'Lebo', 'Oratile', 'James', 'James', 'Thabo']


def find_duplicates(names):
    for name in names:
        if names.count(name) > 1:
            return name
    return 'N/A'


print(find_duplicates(names))
  • Related