0% found this document useful (0 votes)
6 views

Python Tutorial_ Sets and Frozen Sets

This document is a tutorial on Python's implementation of sets and frozensets, explaining their characteristics, creation, and operations. It covers the differences between mutable sets and immutable frozensets, as well as various set operations such as union, intersection, and difference. The tutorial also provides examples of how to use sets in Python programming.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Tutorial_ Sets and Frozen Sets

This document is a tutorial on Python's implementation of sets and frozensets, explaining their characteristics, creation, and operations. It covers the differences between mutable sets and immutable frozensets, as well as various set operations such as union, intersection, and difference. The tutorial also provides examples of how to use sets in Python programming.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Dictionaries


Next Chapter: An Extensive Example Using Sets

Sets and Frozensets

Follow Bernd Klein,


the author of this
Introduction website, at Google+:
Bernd Klein on
Python 3 Google
In this chapter of our tutorial, we are dealing with Python's implementation of sets. Though sets are nowadays an integral part of modern mathematics, this has not always
Tutorial been like this. The set theory had been rejected by many, even great thinkers. One of them was the philosopher Wittgenstein. He didn't like the set theory and complained
Bernd Klein on
mathematics is "ridden through and through with the pernicious idioms of set theory...". He dismissed the set theory as "utter nonsense", as being "laughable" and "wrong".
The Origins of Facebook
His criticism appeared years after the death of the German mathematician Georg Cantor, the founder of the set theory. David Hilbert defended it from its critics by famously
Python declaring: "No one shall expel us from the Paradise that Cantor has created.
Starting with
Python: The Search this website:
Cantor defined a set at the beginning of his "Beiträge zur Begründung der transfiniten Mengenlehre":
Interactive Shell "A set is a gathering together into a whole of definite, distinct objects of our perception and of our thought - which are called elements of the set." Nowadays, we can say in
Executing a "plain" English: A set is a well defined collection of objects. Go
Script
The elements or members of a set can be anything: numbers, characters, words, names, letters of the alphabet, even other sets, and so on. Sets are usually denoted with This topic in German
Indentation
capital letters. This is not the exact mathematical definition, but it is good enough for the following. / Deutsche
Data Types and
Übersetzung:
Variables The data type "set", which is a collection type, has been part of Python since version 2.4. A set contains an unordered collection of unique and immutable objects. The set Mengen
Operators data type is, as the name implies, a Python implementation of the sets as they are known from mathematics. This explains, why sets unlike lists or tuples can't have multiple
Sequential Data occurrences of the same element. Python 3
Types: Lists and
Strings This is a tutorial in
List Sets Python3, but this
Manipulations chapter of our course
Shallow and If we want to create a set, we can call the built-in set function with a sequence or another iterable object: is available in a
Deep Copy version for Python
Dictionaries In the following example, a string is singularized into its characters to build the resulting set x: 2.x as well: Sets and
Sets and Frozen Frozen Sets in Python
>>> x = set("A Python Tutorial") 2.x
Sets >>> x
An Extensive {'A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'}
>>> type(x) Classroom
Example Using
<class 'set'> Training
Sets >>> Courses
input via the
keyboard
The goal of this
Conditional website is to provide
Statements We can pass a list to the built-in set function, as we can see in the following:
educational material,
Loops, while allowing you to learn
Loop >>> x = set(["Perl", "Python", "Java"]) Python on your own.
For Loops >>> x Nevertheless, it is
Difference {'Python', 'Java', 'Perl'} faster and more
>>> efficient to attend a
between
"real" Python course
interators und
in a classroom, with
Iterables
an experienced
Output with Print Now, we want to show what happens, if we pass a tuple with reappearing elements to the set function - in our example the city "Paris": trainer. So why not
Formatted output attend one of the live
with string Python courses in
>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
modulo and the >>> cities Strasbourg, Paris,
format method {'Paris', 'Birmingham', 'Lyon', 'London', 'Berlin'} Luxembourg,
Functions >>> Amsterdam, Zürich /
Zurich, Vienna /
Recursion and
Wien, London, Berlin,
Recursive
Munich, Hamburg,
Functions Frankfurt or Lake
As we have expected, no doublets are in the resulting set of cities.
Parameter Constance by Bernd
Passing in Klein, the author of
Immutable Sets
Functions this tutorial?
Namespaces Sets are implemented in a way, which doesn't allow mutable objects. The following example demonstrates that we cannot include, for example, lists as elements:
Global and Local
Variables >>> cities = set((("Python","Perl"), ("Paris", "Berlin", "London"))) Onsite Training
>>> cities = set((["Python","Perl"], ["Paris", "Berlin", "London"])) Courses
Decorators
Traceback (most recent call last):
Memoization with File "<stdin>", line 1, in <module>
Decorators TypeError: unhashable type: 'list' Let us come to your
>>> company,
Read and Write
organization or
Files
institute and train
Modular your employees, as
Programming we've done it many
and Modules times in Amsterdam
Frozensets
Packages in (The Netherlands),
Python Berlin (Germany),
Though sets can't contain mutable objects, sets are mutable:
Regular Bern (Switzerland),
Expressions >>> cities = set(["Frankfurt", "Basel","Freiburg"]) Basel (Switzerland),
>>> cities.add("Strasbourg") Zurich (Switzerland),
Regular
>>> cities Locarno
Expressions, {'Freiburg', 'Basel', 'Frankfurt', 'Strasbourg'} (Switzerland), Den
Advanced >>> Haag (The Hague),
Lambda Hamburg (Germany),
Operator, Filter, Frankfurt (Germany),
Reduce and Map Frozensets are like sets except that they cannot be changed, i.e. they are immutable: Toronto (Canada),
List Edmonton (Canada),
>>> cities = frozenset(["Frankfurt", "Basel","Freiburg"])
Comprehension >>> cities.add("Strasbourg") Munich (Germany)
Traceback (most recent call last): and many other
Iterators and
File "<stdin>", line 1, in <module> cities. We do training
Generators
AttributeError: 'frozenset' object has no attribute 'add' courses in England,
Exception >>> Switzerland,
Handling Liechtenstein,
Tests, DocTests, Austria, Germany,
UnitTests France, Belgium, the
Object Oriented Netherlands,
Programming Improved notation Luxembourg, Poland,
Class and UK, Italy and other
We can define sets (since Python2.6) without using the built-in set function. We can use curly braces instead: locations in Europe
Instance
and in Canada.
Attributes >>> adjectives = {"cheap","expensive","inexpensive","economical"}
Properties vs. >>> adjectives This way you will get
getters and {'inexpensive', 'cheap', 'expensive', 'economical'} a perfect training up
>>>
setters to your needs and it
Inheritance will be extremely cost
Multiple efficient as well.
Inheritance Contact us so we can
Set Operations define and find the
Magic Methods
best course
and Operator
curriculum to meet
Overloading add(element)
your needs, and
OOP, Inheritance A method which adds an element, which has to be immutable, to a set. schedule course
Example sessions to be held at
Slots >>> colours = {"red","green"} your location.
>>> colours.add("yellow")
Classes and
>>> colours
Class Creation {'green', 'yellow', 'red'}
Road to >>> colours.add(["black","white"]) Skilled Python
Metaclasses Traceback (most recent call last): Programmers
File "<stdin>", line 1, in <module>
Metaclasses TypeError: unhashable type: 'list'
Metaclass Use >>> You are looking for
Case: Count experienced Python
Of course, an element will only be added, if it is not already contained in the set. If it is already contained, the method call has no effect. developers or
Function Calls
programmers? We
Abstract Classes
can help you, please
clear() contact us.
Russell's
All elements will be removed from a set.
paradox Quote of the
>>> cities = {"Stuttgart", "Konstanz", "Freiburg"} Day:
The set of all sets >>> cities.clear()
that are not >>> cities
set() "Much of my work
members of has come from being
>>>
themselves". This is a lazy. I didn't like
contradiction since writing programs,
this set must be both copy and so, when I was
a member of itself, working on the IBM
and not a member of Creates a shallow copy, which is returned.
701, writing
itself. programs for
>>> more_cities = {"Winterthur","Schaffhausen","St. Gallen"}
>>> cities_backup = more_cities.copy() computing missile
>>> more_cities.clear() trajectories, I started
This website is >>> cities_backup work on a
created by: {'St. Gallen', 'Winterthur', 'Schaffhausen'} programming system
>>> to make it easier to
write programs."
(John W. Backus)
Just in case, you might think, an assignment might be enough:

>>> more_cities = {"Winterthur","Schaffhausen","St. Gallen"}


>>> cities_backup = more_cities
>>> more_cities.clear()
>>> cities_backup
set() Data Protection
>>> Declaration

The assignment "cities_backup = more_cities" just creates a pointer, i.e. another name, to the same data structure. Data Protection
Declaration
Python Training
Courses in Toronto, difference()
Canada This method returns the difference of two or more sets as a new set.
On site trainings in
Europe, Canada and >>> x = {"a","b","c","d","e"}
the US. >>> y = {"b","c"}
>>> z = {"c","d"}
>>> x.difference(y)
{'a', 'e', 'd'}
>>> x.difference(y).difference(z)
{'a', 'e'}
>>>

Instead of using the method difference, we can use the operator "-":

>>> x - y
{'a', 'e', 'd'}
>>> x - y - z
{'a', 'e'}
>>>

difference_update()
The method difference_update removes all elements of another set from this set. x.difference_update(y) is the same as "x = x - y"

>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> x.difference_update(y)
>>>
>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> x = x - y
>>> x
{'a', 'e', 'd'}
>>>

discard(el)
An element el will be removed from the set, if it is contained in the set. If el is not a member of the set, nothing will be done.

>>> x = {"a","b","c","d","e"}
>>> x.discard("a")
>>> x
{'c', 'b', 'e', 'd'}
>>> x.discard("z")
>>> x
{'c', 'b', 'e', 'd'}
>>>

remove(el)
works like discard(), but if el is not a member of the set, a KeyError will be raised.

>>> x = {"a","b","c","d","e"}
>>> x.remove("a")
>>> x
{'c', 'b', 'e', 'd'}
>>> x.remove("z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>

union(s)
This method returns the union of two sets as a new set, i.e. all elements that are in either set.

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x.union(y)
{'d', 'a', 'g', 'c', 'f', 'b', 'e'}

This can be abbreviated with the pipe operator "|":

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x | y
{'d', 'a', 'g', 'c', 'f', 'b', 'e'}
>>>

intersection(s)
Returns the intersection of the instance set and the set s as a new set. In other words: A set with all the elements which are contained in both sets is returned.

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x.intersection(y)
{'c', 'e', 'd'}
>>>

This can be abbreviated with the ampersand operator "&":

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d","e","f","g"}
>>> x & y
{'c', 'e', 'd'}
>>>

isdisjoint()
This method returns True if two sets have a null intersection.

>>> x = {"a","b","c"}
>>> y = {"c","d","e"}
>>> x.isdisjoint(y)
False
>>>
>>> x = {"a","b","c"}
>>> y = {"d","e","f"}
>>> x.isdisjoint(y)
True
>>>

issubset()
x.issubset(y) returns True, if x is a subset of y. "<=" is an abbreviation for "Subset of" and ">=" for "superset of"
"<" is used to check if a set is a proper subset of a set.

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d"}
>>> x.issubset(y)
False
>>> y.issubset(x)
True
>>> x < y
False
>>> y < x # y is a proper subset of x
True
>>> x < x # a set can never be a proper subset of oneself.
False
>>> x <= x
True
>>>

issuperset()
x.issuperset(y) returns True, if x is a superset of y. ">=" is an abbreviation for "issuperset of"
">" is used to check if a set is a proper superset of a set.

>>> x = {"a","b","c","d","e"}
>>> y = {"c","d"}
>>> x.issuperset(y)
True
>>> x > y
True
>>> x >= y
True
>>> x >= x
True
>>> x > x
False
>>> x.issuperset(x)
True
>>>

pop()
pop() removes and returns an arbitrary set element. The method raises a KeyError if the set is empty

>>> x = {"a","b","c","d","e"}
>>> x.pop()
'a'
>>> x.pop()
'c'

Previous Chapter: Dictionaries


Next Chapter: An Extensive Example Using Sets

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like