Lesson
Python Sets
Sets are mutable sequences, like the list. However, sets and lists differ great. Unlike lists, you cannot use append() nor can you index or slice. Although the set has limitations, it has two advantages. The set can only contain unique items, so if there's two or more items that are the same, they will be removed. This can help get rid of duplicates. Secondly, sets can preform set mathematics. This makes Python sets much like mathematical sets. To create a set, you need to use the curly brackets ({} ).
>>> spam = {1, 2, 3}
>>> spam
{1, 2, 3}
>>> eggs = {1, 2, 1, 3, 5, 2, 7, 3, 4}
>>> eggs
{1, 2, 3, 4, 5, 7}
>>> {True, False, True, False, True}
{False, True}
>>> {"hi", "hello", "hey", "hi", "hiya", "sup"}
{'hey', 'sup', 'hi', 'hello', 'hiya'}
 |
Note: If you try to create an empty set (a set with no items in it) you'll end up creating a dictionary. This is because the dictionary also uses the curly brackets. If you want to create an empty set, you'll need to do something like spam = set() . Also, an empty set will return set() so there's no confusion with dictionaries. |
|