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'}


Attention yellow.svg 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.

This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us  |  About |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books