Lesson 11Diving Deeper into Data Structures: Sets

We've seen how to use lists, tuples, and dictionaries to store data. In this lesson, we tackle one final basic data structure: sets. A set is an unordered collection of items in which every set element is unique and must be immutable (cannot be changed). A set itself, however, is mutable. We can add or remove items from it.

SETS

As mentioned, a set is an unordered and unindexed collection of unique items. Specifically:

  • The values stored in a set are not indexed in any way. To retrieve an item from a set, you use the value itself, rather than an index.
  • Each item in a set must be unique. You cannot include multiple items with the same value in the same set.
  • The contents of a set are not ordered. You can add the items in any order you wish, and Python will typically retrieve them in a different, random order.

The steps to create a set are similar to those used to create other data collections, such as lists and tuples. The main difference is the use of curly braces ({}) to define the collection as a set.

It is important that we differentiate dictionaries from sets. Dictionaries and sets are almost identical, except that sets do ...

Get Job Ready Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.