Set Operations in Python

 
Sets
 
Ruth Anderson
UW CSE 160
Spring 2018
 
1
Sets
 
Mathematical set:  a collection of values, without
duplicates or order
Order does not matter
{ 1, 2, 3 } == { 3, 2, 1 }
No duplicates
{ 3, 1, 4, 1, 5 } == { 5, 4, 3, 1 }
For every data structure, ask:
How to create
How to query (look up) and perform other operations
(Can result in a new set, or in some other datatype)
How to modify
Answer:  
http://docs.python.org/2/library/stdtypes.html#set
 
3
 
2
 
1
 
1
 
4
 
3
 
5
2
 
Two ways to create a set
 
1.
Direct mathematical syntax:
odd = { 1, 3, 5 }
prime = { 2, 3, 5 }
Note: Cannot use “
{}
”  to express empty set: it means
something else 
.
2.
Construct from a 
list:
 
 
(also from a tuple or string)
odd = set( [1, 3, 5] )
prime = set( [2, 3, 5] )
empty = set( [] ) # or set( )
    
Python always 
prints
 using this syntax above
 
 
3
Set operations
 
odd = { 1, 3, 5 }
prime = { 2, 3, 5 }
 
membership 
 
Python: 
in
 
4 in prime 
 False
union 
  
Python: 
|
 
odd | prime 
 { 1, 2, 3, 5 }
intersection  
 
Python: 
&
 
odd & prime 
 { 3, 5 }
difference \ or -
 
Python: 
-
 
odd – prime 
 { 1 }
 
 
Think in terms of 
set operations
,
 
not
 in terms of iteration and element operations
Shorter, clearer, less error-prone, faster
 
Although we can do iteration over sets:
# iterates over items in 
arbitrary
 order
for item in myset:
But we 
cannot
 index into a set to access a specific element.
4
 
Modifying a set
 
Add
 
one element to a set:
myset.add(newelt)
myset = myset | { newelt }
 
Remove
 
one element from a set:
myset.remove(elt)  
# elt must be in 
myset
 
or raises err
myset.discard(elt) 
# never errs
myset = myset - { elt }
What would this do?
myset = myset – elt
 
Remove and return an arbitrary element from a set:
myset.pop()
 
5
Note
: 
add
, 
remove
 and 
discard
 all return 
None
 
Practice with sets
 
z = {5, 6, 7, 8}
y = {1, 2, 3, "foo", 1, 5}
k = z & y
j = z | y
m = y – z
n = z – y
p = z
q = set(z)
z.add(9)
 
6
See in python tutor
List
 
vs. 
set
 operations (1)
 
Find the common elements 
in both 
list1 
and 
list2
:
out1 = []
for i in list2:
    if i in list1:
        out1 .append(i)
 
# Aside: We will learn about list comprehensions later
out1 
= [i for i in list2 if i in list1]
-----------------------------------------------------------------------
Find the common elements 
in both 
set1
 and 
set2
:
set1 & set2
 
Much shorter, clearer, easier to write with sets!
7
List
 
vs. 
set
 operations(2)
 
Find elements in 
either
 
list1 
or 
list2 
(
or both
) (without duplicates):
out2 = list(list1)
  
# make a copy
for i in list2:
    if i not in list1:
 
# don’t append elements already in out2
        out2.append(i)
 
Another way:
out2 = list1+list2
for i in out1:                  # out1 = common elements in both lists
    out2.remove(i)         # Remove common elements
-----------------------------------------------------------------------
Find the elements in 
either
 
set1 
or 
set2 
(
or both
):
set1 | set2
8
List
 
vs. 
set
 operations(3)
 
Find the elements in 
either 
list 
but 
not
 in both
:
out3 = []
for i in list1+list2:
    if i not in list1 or i not in list2:
        out3.append(i)
----------------------------------------------------------------
Find the elements in 
either 
set
 
but 
not
 in both
:
set1 ^ set2
 
9
 
Not every value may be placed in a 
set
 
Set 
elements
 must be 
immutable
 values
int, float, bool, string, 
tuple
not
:  list, set, dictionary
The set itself is 
mutable
 (e.g. we can add and remove
elements)
Goal
:  only set operations change the set
after “
myset.add(x)
”,  
x in myset
 
 
True
y in myset
  always evaluates to the same value
Both conditions should hold until 
myset
 
is changed
Mutable elements can violate these goals
Aside: 
frozenset
 must contain immutable values and is
itself immutable (cannot add and remove elements)
 
10
 
Not every value may be placed in a set
 
Set elements must be immutable values
int, float, bool, string, 
tuple
not
:  list, set, dictionary
Goal:  only set operations change the set
after “
myset.add(x)
”,  
x in myset
 
 
True
y in myset
  always evaluates to the same value
Both conditions should hold until 
myset
 itself 
is changed
Mutable elements can violate these goals
list1 = ["a", "b"]
list2 = list1
list3 = ["a", "b"]
myset = { list1 }
 
 
Hypothetical; actually illegal in Python!
list1 in myset 
 True
list3 in myset 
 True
list2.append("c")
 
 
 
not modifying  
myset 
“directly”
list1 in myset 
 ???
 
  m
odifying  
myset 
“indirectly” would lead to different results
list3 in myset 
 ???
 
11
Slide Note
Embed
Share

Explore the concept of sets in Python, including how to create and modify sets, perform set operations, and differentiate between lists and sets. Learn about direct mathematical syntax, constructing sets from lists, modifying sets, and practicing with sets using Python. Discover the advantages of using sets for efficient and error-free operations in Python.

  • Python
  • Sets
  • Operations
  • Data Structures
  • Syntax

Uploaded on Sep 25, 2024 | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Sets Ruth Anderson UW CSE 160 Spring 2018 1

  2. Sets Mathematical set: a collection of values, without duplicates or order Order does not matter { 1, 2, 3 } == { 3, 2, 1 } No duplicates { 3, 1, 4, 1, 5 } == { 5, 4, 3, 1 } For every data structure, ask: How to create How to query (look up) and perform other operations (Can result in a new set, or in some other datatype) How to modify Answer: http://docs.python.org/2/library/stdtypes.html#set 2 3 1 4 5 1 3 2

  3. Two ways to create a set 1. Direct mathematical syntax: odd = { 1, 3, 5 } prime = { 2, 3, 5 } Note: Cannot use {} to express empty set: it means something else . 2. Construct from a list: (also from a tuple or string) odd = set( [1, 3, 5] ) prime = set( [2, 3, 5] ) empty = set( [] ) # or set( ) Python always prints using this syntax above 3

  4. Set operations odd = { 1, 3, 5 } prime = { 2, 3, 5 } membership union intersection difference \ or - 4 in prime False odd | prime { 1, 2, 3, 5 } odd & prime { 3, 5 } odd prime { 1 } Python: in Python: | Python: & Python: - Think in terms of set operations, not in terms of iteration and element operations Shorter, clearer, less error-prone, faster Although we can do iteration over sets: # iterates over items in arbitrary order for item in myset: But we cannot index into a set to access a specific element. 4

  5. Modifying a set Add one element to a set: myset.add(newelt) myset = myset | { newelt } Remove one element from a set: myset.remove(elt) # elt must be in mysetor raises err myset.discard(elt) # never errs myset = myset - { elt } What would this do? myset = myset elt Remove and return an arbitrary element from a set: myset.pop() Note: add, remove and discard all return None 5

  6. See in python tutor Practice with sets z = {5, 6, 7, 8} y = {1, 2, 3, "foo", 1, 5} k = z & y j = z | y m = y z n = z y p = z q = set(z) z.add(9) 6

  7. Listvs. set operations (1) Find the common elements in both list1 and list2: out1 = [] for i in list2: if i in list1: out1 .append(i) # Aside: We will learn about list comprehensions later out1 = [i for i in list2 if i in list1] ----------------------------------------------------------------------- Find the common elements in both set1 and set2: set1 & set2 Much shorter, clearer, easier to write with sets! 7

  8. Listvs. set operations(2) Find elements in either list1 or list2 (or both) (without duplicates): out2 = list(list1) # make a copy for i in list2: if i not in list1: # don t append elements already in out2 out2.append(i) Another way: out2 = list1+list2 for i in out1: # out1 = common elements in both lists out2.remove(i) # Remove common elements ----------------------------------------------------------------------- Find the elements in either set1 or set2 (or both): set1 | set2 8

  9. Listvs. set operations(3) Find the elements in either list but not in both: out3 = [] for i in list1+list2: if i not in list1 or i not in list2: out3.append(i) ---------------------------------------------------------------- Find the elements in either setbut not in both: set1 ^ set2 9

  10. Not every value may be placed in a set Set elements must be immutable values int, float, bool, string, tuple not: list, set, dictionary The set itself is mutable (e.g. we can add and remove elements) Goal: only set operations change the set after myset.add(x) , x in myset True y in myset always evaluates to the same value Both conditions should hold until mysetis changed Mutable elements can violate these goals Aside: frozenset must contain immutable values and is itself immutable (cannot add and remove elements) 10

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#