Sets

Sets

A set holds values without duplicates and without a defined order. set(...) builds one from a list, dropping repeats:

tags = set(["news", "sport", "news", "local"])
print(len(tags))

Output:

3

The duplicate "news" collapsed into one. in checks membership, and add inserts a value — adding a value already present changes nothing:

print("sport" in tags)
tags.add("weather")
tags.add("sport")
print(len(tags))

Output:

True
4

Sets exist for exactly these two jobs: removing duplicates and fast membership checks. They have no indexing — tags[0] is an error, because a set has no positions.

Exercise

  1. Define a function named unique_count with one parameter, items (a list). It returns how many distinct values the list contains.
  2. Define a function named has_duplicates with one parameter, items. It returns True when at least one value appears more than once.

unique_count(["a", "b", "a"]) returns 2. has_duplicates(["a", "b", "a"]) returns True.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestSets(unittest.TestCase):
    def test_unique_count_with_a_repeat(self):
        self.assertEqual(unique_count(["a", "b", "a"]), 2)

    def test_unique_count_of_empty_list(self):
        self.assertEqual(unique_count([]), 0)

    def test_has_duplicates_when_a_value_repeats(self):
        self.assertIs(has_duplicates(["a", "b", "a"]), True)

    def test_no_duplicates_in_distinct_values(self):
        self.assertIs(has_duplicates([1, 2, 3]), False)
def unique_count(items):
    return len(set(items))


def has_duplicates(items):
    return len(set(items)) != len(items)


print(unique_count(["a", "b", "a"]))
print(has_duplicates(["a", "b", "a"]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.