Sets Simplify Data Processing5:03 with AJ Tran
Sets can be useful when trying to remove duplicates from a list.
# Sort and Deduplicate a list (not using sets) numbers = [3,1,2,2,1,3,3,1,2] unique_numbers =  # enumerate will track the index while looping for index, number in enumerate(sorted(numbers)): if index == 0: unique_numbers.append(number) elif number == unique_numbers[-1]: pass else: unique_numbers.append(number) unique_numbers #=> [1,2,3]
# Sort and Deduplicate a list (using sets) numbers = [3,1,2,2,1,3,3,1,2] unique_numbers = sorted(set(numbers)) unique_numbers #=> [1,2,3]
Here are more "constructor" functions that convert sets into other collection types:
list() - convert a set into a list. elements may be in random order.
tuple() - convert a set into a tuple. elements may be in random order.
frozenset() - convert a set into a frozen set. A frozenset is an immutable set. As a list is to a tuple, a set is to a frozenset.
Frozensets are not commonly used so I will mention some examples here as a technical note.
- Frozensets can be used as dictionary keys, ie. the dictionary key is like an "unordered tuple."
- Frozensets are used in the Python source code for tests and documenting implementation details.
- Frozensets can be practical for unit testing, eg. to test that the keys of a dictionary are equal to an expected, immutable frozenset of keys.
You need to sign up for Treehouse in order to download course files.Sign up