Sets

Use example: find unique elements

a = "banana"
unique = set(a)
print(unique) # all the letters used in the string 'banana'
{'n', 'b', 'a'}
  • Later, for example, you may want to use this set as the keys for a dictionary counting the number of occurrences.
occurrences = {u:0 for u in unique}
for character in a:
  occurrences[character] += 1
print(occurrences)
{'n': 2, 'b': 1, 'a': 3}

Use example: set operations

  • Another application of sets is to perform mathematical operations such as union, intersection, difference, and symmetric difference. These operations can be useful in various scenarios, such as data analysis, where you need to combine or compare sets of data.

  • Suppose my wife and I had two book collections before getting married. Then…
fernando = {"The Lord of the Rings", "Out of the Silent Planet", "The Chronicles of Narnia", "The Silmarillion"}
jemima = {"Harry Potter", "Pride and Prejudice", "The Lord of the Rings", "The Chronicles of Narnia", "The Hobbit"}

all_books = fernando.union(jemima)
print("All Books:", all_books)
All Books: {'Pride and Prejudice', 'The Lord of the Rings', 'The Hobbit', 'The Chronicles of Narnia', 'Out of the Silent Planet', 'Harry Potter', 'The Silmarillion'}
  • But let’s suppose we also want to compare our collections:
# Union of the two sets (books that we both have)
common_books = fernando.intersection(jemima)
print("Common books:", common_books)

# Difference between the two sets (books that Fernando has and Jemima doesn't)
unique_to_fernando = fernando.difference(jemima) # OR: fernando - jemima
print("Books unique to Fernando:", unique_to_fernando)

# Symmetric difference (books that either Fernando has or Jemima has)
unique_books = fernando.symmetric_difference(jemima)
print("Unique books in both collections:", unique_books)
Common books: {'The Chronicles of Narnia', 'The Lord of the Rings'}
Books unique to Fernando: {'Out of the Silent Planet', 'The Silmarillion'}
Unique books in both collections: {'Harry Potter', 'Pride and Prejudice', 'Out of the Silent Planet', 'The Silmarillion', 'The Hobbit'}

Set methods

  • All the methods you can use with sets can be found in the documentation.

  • You can also use set comprehensions. For example, what’s the output of the following code?

a = {x for x in 'abracadabra' if x not in 'abc'}