Skip to content
Laviyx Learn

Try

Python Lab · Experiment 15

Check if a list has duplicates using a function

PythonWeek 4JNTUH R22 · CS206ES

Aim

To write a Python function has_duplicates that takes a list and returns True if any element appears more than once, without changing the original list, and to test it on several lists.

Algorithm

  1. Define the function has_duplicates(items).
  2. Make a sorted copy of the list with sorted(items). The original list is not touched.
  3. In the sorted copy, equal values sit next to each other. Compare each item with the next one.
  4. If two neighbours are equal, return True.
  5. If no equal neighbours are found, return False.
  6. Test the function on lists with and without repeats, and print the original list after the call to show it has not changed.

Program

Python
def has_duplicates(items):
    """Return True if any element of items appears more than once."""
    copy = sorted(items)  # a new list; items itself is not changed
    for i in range(len(copy) - 1):
        if copy[i] == copy[i + 1]:
            return True
    return False


test_lists = [
    [4, 1, 7, 3],
    [4, 1, 7, 1, 3],
    ["red", "green", "blue", "green"],
    [],
]

for items in test_lists:
    print(f"has_duplicates({items}) = {has_duplicates(items)}")

numbers = [5, 3, 9, 3]
print()
print("Before the call:", numbers)
print("has_duplicates:", has_duplicates(numbers))
print("After the call :", numbers)

Output

Output
has_duplicates([4, 1, 7, 3]) = False
has_duplicates([4, 1, 7, 1, 3]) = True
has_duplicates(['red', 'green', 'blue', 'green']) = True
has_duplicates([]) = False

Before the call: [5, 3, 9, 3]
has_duplicates: True
After the call : [5, 3, 9, 3]

Recorded by running this exact program.

How it works

The task says the function must not modify the original list. sorted(items) returns a new sorted list, so the caller's list keeps its order. Calling items.sort() instead would reorder the caller's list, because a list passed to a function is the same object, not a copy.

Another common way uses a set: return len(set(items)) < len(items). A set keeps only one copy of each value, so if it is smaller than the list, something was repeated. This works only when the elements are hashable (numbers, strings, tuples), while the sorting method works only when they can be compared with each other.

Common mistakes

  • Calling items.sort() inside the function. It changes the list the caller passed in, which the task does not allow. Use sorted(items), which makes a new list.

  • Comparing every element with every other element including itself, so every list seems to have duplicates. Compare only different positions, or neighbours in a sorted copy.

  • Returning False inside the loop as soon as one pair is different. Return False only after all pairs have been checked.

  • Writing copy = items and then sorting copy. This does not make a copy: both names refer to the same list, so the original is sorted too.

Viva questions

Try to answer each one aloud before you open it.

  • Why does the function sort a copy and not the list itself?

    A list passed to a function is the same object the caller has. Sorting it in place would change the caller's list. sorted() returns a new list and leaves the original as it was.

  • Why does sorting help in finding duplicates?

    After sorting, equal values are next to each other, so one pass comparing neighbours finds any repeat.

  • How can a set be used to check for duplicates?

    A set stores each value only once. If len(set(items)) is less than len(items), some value was repeated.

  • What is the difference between copy = items and copy = items[:]?

    copy = items makes a second name for the same list. items[:] (or items.copy()) makes a new list with the same elements, so changing one does not change the other.

Learn the concepts

All Python Programming Lab experiments →