Python

Sets

Sets in Python are a collection of unordered, unique elements. They are commonly used to store and manipulate data in a more efficient way, as they use a data structure called a hash table which allows for quick membership testing and element insertion and deletion.

One of the main features of sets is that they only allow for unique elements, meaning that if you try to add a duplicate element to a set, it will be ignored and the set will remain unchanged. This can be useful for removing duplicates from a list or for checking if an element is present in a set.

Set Creation

Sets can be created by enclosing a list of elements in curly braces {} or by using the set() function. For example:

my_set = {1, 2, 3}
my_set = set([1, 2, 3])
Set Methods

Sets also have a variety of useful methods that allow you to manipulate and analyze the data they contain. Some common methods include:

  • add(): adds an element to the set
  • remove(): removes an element from the set
  • union(): returns the union of two sets (all elements present in either set)
  • intersection(): returns the intersection of two sets (only elements present in both sets)
  • difference(): returns the difference between two sets (elements present in the first set but not the second)
set_1 = {1, 2, 3, 4, 5}
set_2 = {3, 4, 5, 6, 7}
set_1.add(3)
# Output {1, 2, 3, 4, 5}
set_1.remove(5)
# Output {1, 2, 3, 4}
set_1.union(set_2)
# Output {1, 2, 3, 4, 5, 6, 7}
set_1.intersection(set_2)
# Output {3, 4}
set_1.difference(set_2)
# Output {1, 2}

Sets are often used in combination with other data types, such as lists and dictionaries, to perform more advanced operations. For example, you can use the intersection() method to find common elements between two lists, or use sets to check if a list contains unique elements.

In conclusion, sets are a powerful and efficient tool for storing and manipulating data in Python. They can be used to perform a variety of tasks, such as removing duplicates, finding common elements, and testing for membership.