Python
Topics:
Set
• Getting Started
• Working with Data
• Object Oriented Programming
• Iterators and Generators
• Functional Programming

# Set

• Tutorial

## Sets

A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated.

Sets are commonly used for membership testing, removing duplicates entries, and also for operations such as intersection, union, and set difference.

In this tutorial you will learn how to create a set and and the common paradigms for a set in Python.

## How to create Sets

Sets can be created by calling the built-in set() function with a sequence or another iterable object.

>>> #creating an empty set
>>> setA = set()
>>> print(setA)
set()

>>> # creating a set with a string.
>>> # since a string is an iterable, this will succeed.
>>> setA = set("HackerEarth")
>>> print(setA)
{'h', 'H', 't', 'k', 'e', 'c', 'E', 'a', 'r'}

>>> # creating a set with a list
>>> setA = set(["C", “C++”, “Python”])
>>> print(setA)
{'C', 'Python', 'C++'}

>>> # creating a set with a list of numbers
>>> # there are some duplicates in it.
>>> setA = set([1, 2, 3, 4, 5, 6, 7, 7, 7])
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7}

>>> # creating a set with a string. The string has some repeated characters.
>>> myString = 'foobar'
>>> setA = set(myString)
>>> print(setA)
{'r', 'a', 'b', 'f', 'o'}


set(object) iterates over the elements present in object and adds all the unique elements to the set.

Next you will learn about different operations available for Python Sets.

For all set operations, the set created below which is a set of integers. There are some integers that are repeated here. :

>>> setA = set([1, 2, 3, 4, 5, 6, 7, 7, 7])
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7}


## Methods to change a set

### How to add elements to a set

This will add element to a set:

For example, you can add the element 8 to the set 8

    >>> setA.add(8)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8}


Or you can add a tuple (9, 10) to the setA and the new set will consist of the tuple as well.

    >>> setA.add((9, 10))
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8, (9, 10)}

• Python set update(element)

Adds element to list; it is an in-place set union operation.

For example you can pass a list to the update method and this will update the setA with the elements.

    >>> # pass a list with elements 11 and 12
>>> setA.update([11, 12])
>>> # check if setA is updated with the elements.
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8, 11, 12, (9, 10)}


Similarly you can update with a list and a new set as shown below

    >>> setA.update([12, 14], {15, 16})
>>> print(setA)
{1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 14, 15, (9, 10), 16}


Using add, elements can be added but not another iterable like set, list, or tuple. Update can be used to add iterable or iterables of hashable elements.

### Methods to remove elements from a set

Python set discard(element) and remove(element) Used to remove element from the set

>>> # removes element 7 from set
>>> print(setA)
{1, 2, 3, 4, 5, 6, 8, 11, 12, 14, 15, (9, 10), 16}

>>> # removes element 8 from set
>>> setA.remove(8)
>>> print(setA)
{1, 2, 3, 4, 5, 6, 11, 12, 14, 15, (9, 10), 16}


Both discard and remove take a single argument, the element to be deleted from the set. If the value is not present, discard() does not do anything. Whereas, remove will raise a KeyError exception.

>>> # discard doesn’t do anything is value to be discarded is not present
>>> print(setA)
{1, 2, 3, 4, 5, 6, 11, 12, 14, 15, (9, 10), 16}

>>> # this operation fails with an exception being raised
>>> setA.remove(19)
Traceback (most recent call last):
File "python", line 1, in <module>
KeyError: 19


### Other useful set methods

• Python set copy() Creates a shallow copy of the set with which it is called
>>> shallow_copy_of_setA = setA.copy()
>>> print(shallow_copy_of_setA)
{1, 2, 3, 4, 5, 6, 11, 12, 14, 15, (9, 10), 16}


Using assignment here instead of copy() will create a pointer to the already existing set.

• Python set clear() Will remove all elements from set

>>> # clear the set shallow_copy_of_setA created before using copy() operation
>>> shallow_copy_of_setA.clear()
>>> print(shallow_copy_of_setA)
set()

• Python set pop() Removes an arbitrary set element

>>> # popping an element from setA
>>> setA.pop()
1
>>> # pop raises a KeyError exception if the set is empty
>>> shallow_copy_of_setA.pop()
Traceback (most recent call last):
File "python", line 1, in <module>
KeyError: 'pop from an empty set'


## Set Operations

• Set Intersection using intersection(s) Returns element present in both sets; this can also be achieved using the ampersand operator (&).

>>> # create a new set setB
>>> setB= set()

>>> # update setB with values
>>> setB.update([1, 2, 3, 4, 5, 10, 15, 22])
>>> print(setB)
{1, 2, 3, 4, 5, 10, 15, 22}

>>> # print a new set with the values present in both setA and setB
>>> print(setA & setB)
{2, 3, 4, 5, 15}

>>> # above operation and using method name intersection shows same results
>>> setA.intersection(setB)
{2, 3, 4, 5, 15}

• Set Difference using difference() Returns the difference of two sets; “-” operator can also be used to find the set difference.

>>> # print a new set with values present in setA but not in setB
>>> setA.difference(setB)
{6, 11, 12, 14, (9, 10), 16}

>>> # this returns empty set
>>> setB.difference(setA)
set()


setB is a proper subset of setA to setB - setA is empty set.

### Other Set Operations

• Python set isdisjoint() Returns true if intersection of sets is empty otherwise false

>>> # returns false as both have common elements
>>> setA.isdisjoint(setB)
False

>>> # create a new empty set setC
>>> setC = set()
>>> # update setC with values
>>> setC.update([100, 99])

>>> # returns true as setA and setC has no elements in common
>>> setA.disjoint(setC)
True

• Python set difference_update() setA.difference_update(setB) removes all elements of y from setA; ‘-=’ can be used in place of the difference_update method.

>>> # update setA by removing elements present in setB from setA
>>> setA.difference_update(setB)
>>> # check the result set
>>> print(setA)
{6, 11, 12, 14, (9, 10), 16}


Similarly, setA.intersection_update(setB) removes elements from setA which are not present in the intersection set of setA and setB. ‘&=’ can be used in place of the intersection_update method.

• Python set issubset() and issuperset() setA.issubset(setB) returns True if setA is subset of setB, False if not. “<=” operator can be used to test for issubset. To check for proper subset “<” is used.
>>> # check if setA is a subset of setB
>>> setA.issubset(setB)
False
>>> # check if set B is a subset of setA
>>> setB.issubset(setA)
False


Let’s make setB a subset of setA by removing values 1, 10, and 22.

    >>> # remove few elements to make setB a subset of setA
>>> setB.remove(1)
>>> setB.remove(10)
>>> setB.remove(22)

>>> # check the values present in setB now
>>> print(setB)
{2, 3, 4, 5, 15}

>>> # issubset now returns true
>>> setB.issubset(setA)
True
>>> setB < setA
True

>>> #setA now becomes a superset of setB
>>> setA.issuperset(setB)
True

Уведомления

?