Python language basics 54: how to copy a set

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Python language basics 54: how to copy a set

  1. Pingback: Python language basics 54: how to copy a set | SutoCom Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: