KKAIROS
Practical guideIllustrative4 min read

Python comprehensions: build a list, dict or set in one line

A comprehension builds a list, dict or set from an iterable in one expression. Only one condition, x % 2 == 0, was run.

Published:

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-52-A: list, dict and set comprehensions build different types from any iterable

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

python3 -c "print([x*x for x in range(3)], {x: x*x for x in range(3)}, sorted({x for x in 'aab'}), [c for c in 'ab'])"

Recorded output:

[0, 1, 4] {0: 0, 1: 1, 2: 4} ['a', 'b'] ['a', 'b']

TE-52-B: a list comprehension with a condition keeps only the items that pass it, and a dict comprehension can be built from zip

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
print([x for x in range(5) if x % 2 == 0])
print({k: v for k, v in zip('ab', [1, 2])})
EOS

Command:

python3 s.py

Recorded output:

[0, 2, 4]
{'a': 1, 'b': 2}

Exit status: 0. The output matches the expected text written before the run.

TE-52-C: expected non-zero exit: an exception inside a comprehension stops the program before print runs

Setup for this run, inside a throwaway directory (mktemp -d):

cat > s.py <<'EOS'
print([1 / x for x in [1, 0]])
EOS

The file ../err.txt sits one level above the working folder, inside the same throwaway tree. The output block below shows only the last line of the error; the full traceback went to ../err.txt.

Command:

python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rc

Recorded output:

ZeroDivisionError: division by zero

Exit status: 1. This status and the output match what was written before the run.

Reading the recorded output

The command prints four values on one line, in the order they appear in the print call. The list comprehension over range(3) gave [0, 1, 4], the squares of 0, 1 and 2. The dict comprehension used the same numbers as keys and squares as values: {0: 0, 1: 1, 2: 4}. The set comprehension ran over the text aab, which has three characters. It is wrapped in sorted(), so it printed as the list ['a', 'b'], and the repeated a appears once. The same command printed the same line under the hash seeds 1 to 5 and under a random seed; those runs are in the log. The last value is a list comprehension over the text ab, which gave ['a', 'b'], one item for each character.

TE-52-B: the condition x % 2 == 0 kept 0, 2 and 4 out of range(5), and the dict comprehension over zip('ab', [1, 2]) gave {'a': 1, 'b': 2}. TE-52-C: the list comprehension reached the item 0 in [1, 0] and the program stopped with ZeroDivisionError: division by zero and exit status 1. The print call did not run, so no partial list was shown.

Ad

Limits

The run shows list, dict and set comprehensions and a list comprehension over a string. Generator expressions, nesting and timing are not tested on this page. Only one condition, x % 2 == 0, was run. A set has no promised order, so the set comprehension is wrapped in sorted() here; the order of a plain set was not tested.

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-52-A | list, dict and set comprehensions build different types from any iterable | 0 | PASS | ac80edc960f8 | | TE-52-B | a list comprehension with a condition keeps only the items that pass it, and a dict comprehension can be built from zip | 0 | PASS | c4e9568b61a2 | | TE-52-C | expected non-zero exit: an exception inside a comprehension stops the program before print runs | 1 | PASS | ebe890c01c46 |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides