Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.copy() method

Reference for Python set.copy(): return a shallow copy of a set, why plain assignment is not a copy, and how copy() compares to set(s) and frozenset.

The copy() method returns a new set with the same elements. Changing the copy does not change the original, and the other way round.

Plain assignment (b = a) does not copy anything: both names refer to the same set. Use copy() when you want to modify a set while keeping the original intact, for example before calling an in-place method such as difference_update().

Python
a = {1, 2, 3}
b = a.copy()
b.add(4)   # a is still {1, 2, 3}

Try it

Python Assignment versus copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Copy before an in-place operation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.copy()
Name Description
(none) The method takes no arguments.

Return value: a new set of the same type containing the same elements.

Usage notes

  • Shallow copy. Elements are not copied. Set elements must be hashable, and the common ones (numbers, strings, tuples of those, frozensets) are immutable, so this rarely matters.
  • Other ways to copy: set(s) and {*s} give the same result. copy() states the intent most clearly.
  • frozenset.copy() exists and returns the same object, since immutable values need no copy.
  • Cost is linear in the number of elements.
  • Copying is not needed for operations that already return new sets, such as union(), intersection() and difference().