[Python] Sets

[Python] Sets

Sets in Python

Sets are an unordered collection of unique elements. They are similar to lists, but they do not allow duplicate elements. Sets are mutable, which means that they can be changed after they are created.

Creating Sets

Sets can be created using the set() constructor. The set() constructor takes an iterable as its argument, and creates a set from the elements of the iterable. For example, the following code creates a set from the list [1, 2, 3, 4]:

>>> set([1, 2, 3, 4])
{1, 2, 3, 4}

Set Methods

Python provides a number of methods for working with sets. These methods can be used to perform tasks such as:

  • Adding elements to a set
  • Removing elements from a set
  • Checking if an element is in a set
  • Getting the union, intersection, difference, and symmetric difference of two sets

For example, the following code adds the element 5 to the set s:

>>> s = {1, 2, 3, 4}
>>> s.add(5)
>>> s
{1, 2, 3, 4, 5}

The following code removes the element 2 from the set s:

>>> s.remove(2)
>>> s
{1, 3, 4, 5}

The following code checks if the element 3 is in the set s:

>>> 3 in s
True

The following code gets the union of the sets s and t:

>>> s = {1, 2, 3}
>>> t = {4, 5, 6}
>>> s.union(t)
{1, 2, 3, 4, 5, 6}

The following code gets the intersection of the sets s and t:

>>> s.intersection(t)
set()

The following code gets the difference of the sets s and t:

>>> s.difference(t)
{1, 2, 3}

The following code gets the symmetric difference of the sets s and t:

>>> s.symmetric_difference(t)
{1, 2, 3, 4, 5, 6}

Set Iteration

Sets can be iterated over using a for loop. For example, the following code iterates over the set s and prints each element:

>>> for element in s:
...     print(element)
...
1
3
4
5

Set Operations

Sets can be used to perform a variety of set operations, such as union, intersection, difference, and symmetric difference. These operations can be used to combine sets, find common elements between sets, and find elements that are unique to a set.

Exercises

  1. Write a program that asks the user for a list of numbers. Then, use set operations to find the number of unique numbers in the list.
  2. Write a program that reads a file and creates a set of all the words in the file. Then, use set operations to find the number of unique words in the file.
  3. Write a program that generates a random set of numbers. The set should contain at least 10 numbers, and the numbers should be between 1 and 100.

I hope this blog post has helped you to learn about sets in Python.

Leave a Comment