Python sets and tuples

Choose uniqueness or immutable grouping to fit the problem.

Python
first = {1, 2, 3}
second = {3, 4}
print(sorted(first & second))
print(sorted(first | second))
point = (2, 5)
x, y = point
print(x + y)
assert len({1, 1, 2}) == 2
Output
[3]
[1, 2, 3, 4]
7

Explanation

A set stores distinct hashable elements and supports union, intersection, and difference. Set iteration order is not a sorted-order contract, so sorted is used for display.

A tuple groups values in an immutable sequence. It can be a dictionary key when every contained element is hashable. An immutable tuple can still refer to a mutable object.

Explore the dry run
Guided walkthroughReady
1first = {1, 2, 3}
2second = {3, 4}
3print(sorted(first & second))
4print(sorted(first | second))
5point = (2, 5)
6x, y = point
7print(x + y)
8assert len({1, 1, 2}) == 2

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create three unique elements.first = {1, 2, 3}
—
Create another set.second = {3, 4}
—
Intersection keeps the shared element.second = {3, 4}
[3]
Union includes each distinct element once.second = {3, 4}
[3]
[1, 2, 3, 4]
Unpack the two-element tuple.x = 2, y = 5
[3]
[1, 2, 3, 4]
Add the coordinates.x = 2, y = 5
[3]
[1, 2, 3, 4]
7

Cost and common mistakes

Expected linear set-combination work in the input sizes under normal hashing; sorting the result adds O(k log k) time and O(k) storage.

  • {} creates an empty dictionary; use set() for an empty set.
  • A tuple containing a list is not hashable.

Try it yourself

Calculate sorted(first - second).

Reveal answer and reasoning

The result is [1, 2], the elements only in first.

Further reading