Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Sets

A set is a collection of unique values with no particular order. It is written with curly brackets: {"red", "green", "blue"}. Adding a value that is already there changes nothing. Sets answer questions such as "which different values are there?", "is this value in the collection?" and "which values do two collections have in common?" quickly and simply.

Removing duplicates

visits = ["Pune", "Delhi", "Pune", "Goa", "Delhi", "Pune"]
cities = set(visits)
print(len(visits), "visits to", len(cities), "cities")
print(sorted(cities))
print("Goa" in cities, "Agra" in cities)
Output
6 visits to 3 cities
['Delhi', 'Goa', 'Pune']
True False

A set has no order, so Python may print its items in any order. When you need them in order, use sorted, which gives a list. Checking membership with in is very fast for sets, even for millions of items.

Adding and removing

tags = {"python", "code"}
tags.add("learn")
tags.add("python")          # already there: no change
tags.discard("code")
tags.discard("missing")     # no error when it is not there
print(sorted(tags), len(tags))
Output
['learn', 'python'] 2

remove also deletes an item, but raises a KeyError when the item is missing; discard stays quiet. An empty set is written set(), because {} is an empty dictionary.

Set operations

Sets support the operations from mathematics. | is the union (everything in either set), & the intersection (in both), - the difference (in the first but not the second) and ^ the values that are in exactly one of them:

python = {"Asha", "Ravi", "John"}
c_lang = {"Ravi", "Meera", "John"}
print(sorted(python | c_lang))
print(sorted(python & c_lang))
print(sorted(python - c_lang))
print(sorted(python ^ c_lang))
print({"Ravi"} <= python)
Output
['Asha', 'John', 'Meera', 'Ravi']
['John', 'Ravi']
['Asha']
['Asha', 'Meera']
True

<= checks whether one set is a subset of another. The same operations are also available as methods: union, intersection, difference and issubset.

What can go in a set

Set items must be immutable: numbers, strings and tuples are fine, but lists and dictionaries cannot be put in a set. A frozenset is a set that cannot change, which can itself be put in another set or used as a dictionary key.

Practice exercises

  1. Count the different letters in the word "mississippi" with a set.
  2. Given two lists of hobbies, print the hobbies two friends share and the ones only one of them has.
  3. Remove duplicates from a list of numbers and print them sorted.
  4. Check whether all the letters of "tea" appear in "great" using a subset test.