= "banana"
a = set(a)
unique print(unique) # all the letters used in the string 'banana'
{'n', 'b', 'a'}
set()
function can be used to create sets.set()
, not {}
; the latter creates an empty dictionary!{'n', 'b', 'a'}
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'}
# 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'}
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?