8: Set

Section 8.1: Operations on sets

with other sets

# Intersection

 

 

 

 

 

{12345}.intersection({3456})

# {3, 4, 5}

{12345} & {3,

456}

 

# {3, 4, 5}

# Union

 

 

 

 

 

{12345}.union({3456})

# {1, 2, 3, 4, 5, 6}

{12345} | {3,

456}

# {1, 2, 3, 4, 5, 6}

# Difference

 

 

 

 

 

{1234}.difference({235})

# {1, 4}

 

{1234} – {23,

5}

 

# {1, 4}

 

# Symmetric difference with

 

 

 

{1234}.symmetric_difference({235})

# {1, 4, 5}

{1234} ^ {23,

5}

 

 

# {1, 4, 5}

# Superset check

 

 

 

 

 

{12}.issuperset({1,

23}) # False

 

{12>= {123}

 

# False

 

# Subset check

 

 

 

 

 

{12}.issubset({123})

# True

 

 

{12<= {123}

 

# True

 

 

# Disjoint check

 

 

 

 

 

{12}.isdisjoint({3,

4})

# True

 

 

{12}.isdisjoint({1,

4})

# False

 

 

 

 

 

 

 

with single elements

 

 

 

 

# Existence check

 

 

 

 

 

in {1,2,3}

# True

 

 

 

in {1,2,3}

# False

 

 

 

not in {1,2,3}

# True

 

 

 

#Add and Remove{1,2,3}

s.add(4)

# s == {1,2,3,4}

s.discard(3)

# s == {1,2,4}

s.discard(5)

# s ==

{1,2,4}

s.remove(2)

# s ==

{1,4}

s.remove(2)

# KeyError!

Set operations return new sets, but have the corresponding in-place versions:

method

in-place operation

in-place method

union

s |= t

update

intersection

s &= t

intersection_update

dierence

s -= t

dierence_update

symmetric_dierence s ^= tsymmetric_dierence_update

For example:

{12}

s.update({34}) # s == {1, 2, 3, 4}

Section 8.2: Get the unique elements of a list

Let’s say you’ve got a list of restaurants — maybe you read it from a file. You care about the unique restaurants in the list. The best way to get the unique elements from a list is to turn it into a set:

restaurants [“McDonald’s”“Burger King”“McDonald’s”“Chicken Chicken”] unique_restaurants set(restaurants)

print(unique_restaurants)

# prints {‘Chicken Chicken’, “McDonald’s”, ‘Burger King’}

Note that the set is not in the same order as the original list; that is because sets are unordered, just like dicts.

This can easily be transformed back into a List with Python’s built in list function, giving another list that is the same list as the original but without duplicates:

list(unique_restaurants)

# [‘Chicken Chicken’, “McDonald’s”, ‘Burger King’]

It’s also common to see this as one line:

#Removes all duplicates and returns another listlist(set(restaurants))

Now any operations that could be performed on the original list can be done again.

Section 8.3: Set of Sets

{{1,2}{3,4}}

leads to:

TypeError: unhashable type‘set’

Instead, use frozenset:

{frozenset({12})frozenset({34})}

Section 8.4: Set Operations using Methods and Builtins

We define two sets a and b

>>>{12234}

>>>{33445}

NOTE: {1} creates a set of one element, but {} creates an empty dict. The correct way to create an empty set is set().

Intersection

a.intersection(b) returns a new set with elements present in both a and b

>>>a.intersection(b) {34}

Union

a.union(b) returns a new set with elements present in either a and b

>>>a.union(b) {12345}

Dierence

a.difference(b) returns a new set with elements present in a but not in b

>>>a.difference(b) {12}

>>>b.difference(a)

{5}

Symmetric Dierence

a.symmetric_difference(b) returns a new set with elements present in either a or b but not in both

>>>a.symmetric_difference(b) {125}

>>>b.symmetric_difference(a) {125}

NOTEa.symmetric_difference(b) == b.symmetric_difference(a)

Subset and superset

c.issubset(a) tests whether each element of c is in aa.issuperset(c) tests whether each element of c is in a.

>>>{12}

>>>c.issubset(a)

True

>>>a.issuperset(c)

True

The latter operations have equivalent operators as shown below:

 

Method

Operator

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

a.intersection(b)

a

& b

 

 

 

 

 

 

 

 

|

 

 

 

 

 

a.union(b)

 

 

 

 

 

 

a

b

 

 

 

 

 

 

 

 

 

 

a.difference(b)

a – b

 

 

 

 

 

 

 

 

 

a.symmetric_difference(b)

a ^ b

 

 

 

 

 

 

 

 

a.issubset(b)

<= b

 

 

 

 

 

 

 

a.issuperset(b)

>= b

Disjoint sets

Sets a and d are disjoint if no element in a is also in d and vice versa.

>>>{56}

>>>a.isdisjoint(b) # {2, 3, 4} are in both sets False

>>>a.isdisjoint(d)

True

#This is an equivalent check, but less efficient

>>> len(a & d) == True

#This is even less efficient

>>>a & d == set()

True

Testing membership

The builtin in keyword searches for occurances

>>>in a

True

>>>in False

Length

The builtin len() function returns the number of elements in the set

>>>len(a)

4

>>>len(b)

3

Section 8.5: Sets versus multisets

Sets are unordered collections of distinct elements. But sometimes we want to work with unordered collections of elements that are not necessarily distinct and keep track of the elements’ multiplicities.

Consider this example:

>>>setA {‘a’,‘b’,‘b’,‘c’}

>>>setA

set([‘a’‘c’‘b’])

By saving the strings ‘a’‘b’‘b’‘c’ into a set data structure we’ve lost the information on the fact that ‘b’ occurs twice. Of course saving the elements to a list would retain this information

>>>listA [‘a’,‘b’,‘b’,‘c’]

>>>listA

[‘a’‘b’‘b’‘c’]

but a list data structure introduces an extra unneeded ordering that will slow down our computations.

For implementing multisets Python provides the Counter class from the collections module (starting from version 2.7):

Python 2.x Version ≥ 2.7

 

>>>from collections import Counter

>>>counterA Counter([‘a’,‘b’,‘b’,‘c’])

>>>counterA

Counter({‘b’2‘a’1‘c’1})

Counter is a dictionary where where elements are stored as dictionary keys and their counts are stored as dictionary values. And as all dictionaries, it is an unordered collection.

 

 

 

 

 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow. 

*This content is compiled from Stack Overflow Documentation, and the content is written by the beautiful people at Stack Overflow.  This work is licensed under cc by-sa.