Python Sets: unique items and set operations
A set keeps unique items without order. | is union, & is intersection, .difference() removes the items of the other set.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-64-A: set union, intersection and difference on two small sets
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
a = {1, 2, 3, 3}
b = {3, 4}
print(len(a))
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a.difference(b)))
EOSCommand:
python3 s.pyRecorded output:
3
[1, 2, 3, 4]
[3]
[1, 2]Exit status: 0. The output matches the expected text written before the run.
TE-64-B: add puts an item in a set, adding a present item changes nothing, and discard removes an item
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
s = {1, 2}
s.add(2)
s.add(5)
s.discard(1)
print(sorted(s))
EOSCommand:
python3 s.pyRecorded output:
[2, 5]Exit status: 0. This status and the output match what was written before the run.
TE-64-C: expected non-zero exit: remove raises KeyError for an item that is not in the set
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
s = {1, 2}
s.remove(9)
EOSCommand:
python3 s.pyRecorded output: none, standard output was empty.
Standard error from the same run:
Traceback (most recent call last):
File "/tmp/b17-88j0vb3l/work/s.py", line 2, in <module>
s.remove(9)
KeyError: 9Exit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.
TE-64-B: the set started as 1 and 2. Adding 2 again changed nothing, adding 5 and discarding 1 left [2, 5]. TE-64-C: remove(9) stopped with exit status 1. The last line of standard error is KeyError: 9.
Limits
Set order is not defined, so the example prints sorted lists. Items must be hashable, so a list cannot be a set member (not tested).
Source
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-64-A | set union, intersection and difference on two small sets | 0 | PASS | 0ca335eb8cb3 | | TE-64-B | add puts an item in a set, adding a present item changes nothing, and discard removes an item | 0 | PASS | 4c7a1f5e813b | | TE-64-C | expected non-zero exit: remove raises KeyError for an item that is not in the set | 1 | PASS | dc1ba9ed097d |
Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides