Python language basics 54: how to copy a set
October 10, 2015 1 Comment
Introduction
In the previous post we looked at some basic operations from the world of boolean set algebra supported in Python: subset, superset and disjoint. We saw how Python supported these operations natively with built-in functions and also looked at examples which tested them.
In this post we’ll look at 2 ways to create a copy of a set.
Copying a set
We saw previously how to copy lists on this blog here.
Copying a set is a very similar operation. Note that we’re still only talking about a shallow copy with only the references being copied.
The copy function
The copy function operates on the set:
set_start = {4, 6, 3, 5, 9, 8, 7} set_copy = set_start.copy() print(set_start == set_copy) print(set_start is set_copy)
The print statements print True and False respectively.
The set constructor
The set constructor function accepts another set and creates an independent copy. The reference and value equality tests will return the same as above:
set_copy = set(set_start)
In the next post we’ll look at how to get hold of the keys and values of a dictionary.
Read all Python-related posts on this blog here.
Pingback: Python language basics 54: how to copy a set | SutoCom Solutions