Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the set collection


All of the collections we've looked at previously have been sequences: str, bytes, tuple, and list have items which can be accessed by their position within the collection. A set collection is an unordered collection where items are present or absent.

Items in a set collection must be immutable; they must provide a proper hash value as well as an equality test. This means that we can create sets of numbers, strings, and tuples. We can't easily create a set of lists or a set of sets.

The syntax of a set display is a sequence of expressions wrapped in {}.

Here's an example set built using numbers:

>>> fib_set = {1, 1, 3, 5, 8}
>>> fib_set
{8, 1, 3, 5}

We've created a set object by enclosing the values in {}. This syntax looks very similar to the syntax for creating list or tuple. Note that the elements in the set collection are displayed in a different order. There's no guarantee what the order will be; different implementations may show different orders...