Python/Sets

< Python

Objective

  • Learn about Python sets.
  • Learn how to dynamically manipulation sets.
  • Learn about set math and comparison.
  • Learn about built-in set functions.
  • Learn when to use sets and when not to.

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.

Assignments

Completion status: this resource is just getting off the ground. Please feel welcome to help!

This article is issued from Wikiversity - version of the Thursday, April 16, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.