Set Basics
Similar to the way lists use square brackets, sets use curly braces as the notation for the set data type.
You can initialize empty sets like this:
set_a = set()
View on GitHub
Initialize a set with objects:
set_a = set([1, 'a']) set_a = {2, 'b'}
Note that you cannot initialize an empty set with curly braces, even though you can initialize an empty list with square brackets.
This is because that method of initializing is taken by the dictionary data type. Try it out for yourself:
maybe_not_a_set = {} print(type(maybe_not_a_set)) # prints <class 'dict'>
Since sets are unordered data structures, they do not support indexing. You can’t do set_a[0] to get the first element.
Sets are mutable but can only have immutable objects inside them.
Since sets cannot have duplicates inside, all duplicates inside will be removed once the set is constructed or if an element is added to it.
Practice
Set Creator
Create an empty set and print the type of it. Create a set from a given
dictionary(do set(given_dict))
and print it. Note: The set created from the given dictionary contains only the keys of the dictionary.Duplicate Detector
Code a program that detects whether a given list contained duplicate elements, using sets. The output should be in the affirmative if the list contains duplicates of elements, and "no" or "false" or some variation of that if the list contains only unique elements. Assume you do not know the contents of the list. An example list is given.
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.