KKAIROS
Practical guideIllustrative3 min read

Python Tuples and Unpacking

A tuple is an ordered sequence that cannot be changed after creation. Unpacking assigns its items to names in one line, and *rest collects the remainder.

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-65-A: unpacking with a starred name, and assigning to a tuple item raises TypeError

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

cat > s.py <<'EOS'
t = (1, 2, 3, 4)
first, *rest = t
print(first, rest)
try:
    t[0] = 9
except TypeError as e:
    print(type(e).__name__)
EOS

Command:

python3 s.py

Recorded output:

1 [2, 3, 4]
TypeError

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

TE-65-B: a swap and a nested unpacking each assign several names in one line

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

cat > s.py <<'EOS'
a, b = 1, 2
a, b = b, a
print(a, b)
(x, y), z = (1, 2), 3
print(x, y, z)
EOS

Command:

python3 s.py

Recorded output:

2 1
1 2 3

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

TE-65-C: expected non-zero exit: unpacking three items into two names raises ValueError

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

cat > s.py <<'EOS'
a, b = (1, 2, 3)
EOS

Command:

python3 s.py

Recorded output: none, standard output was empty.

Standard error from the same run:

Traceback (most recent call last):
  File "/tmp/b17-ni2cfcbt/work/s.py", line 1, in <module>
    a, b = (1, 2, 3)
ValueError: too many values to unpack (expected 2)

Exit 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-65-B: the swap printed 2 1, and the nested unpacking printed 1 2 3. TE-65-C: unpacking a tuple of three items into two names stopped with exit status 1. The last line of standard error is ValueError: too many values to unpack (expected 2).

Limits

A tuple that holds a list can still change that list inside. Not tested here.

Ad

Source

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-65-A | unpacking with a starred name, and assigning to a tuple item raises TypeError | 0 | PASS | 1d3f6851dd14 | | TE-65-B | a swap and a nested unpacking each assign several names in one line | 0 | PASS | 11db85a039b5 | | TE-65-C | expected non-zero exit: unpacking three items into two names raises ValueError | 1 | PASS | 5d8793a67d68 |

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