Skip to content

Computer Science · Ch 5 — Getting Started with Python

Set

5.7.3

Set

A set is an unordered collection of items, separated by commas and enclosed in curly brackets { }. At first glance a set looks similar to a list — both hold multiple comma-separated items — but two properties set it apart:

  • a set cannot have duplicate entries — every element is unique, and
  • once created, the elements of a set cannot be changed.

Creating and inspecting a set

The textbook's Example 5.6:

#create a set
>>> set1 = {10, 20, 3.14, "New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}

Like a list, a set may mix data types — here an integer, another integer, a float and a string coexist. The type() check confirms the value belongs to <class 'set'>.

Duplicates are silently dropped

The defining behaviour appears when duplicate values are supplied at creation — the set keeps only one copy of each:

#duplicate elements are not included in set
>>> set2 = {1, 2, 1, 3}
>>> print(set2)
{1, 2, 3}
``` …