Why does unpacking a struct result in a tuple?

Think of a use case that loads binary data written using C language. Python won't be able to differentiate if binary data was written using a struct or using a single integer. So, I think, logically it makes sense to return tuple always, since struct pack and unpack perform conversions between Python values and C structs.


Please see doc first struct doc

struct.pack(fmt, v1, v2, ...)

Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

--

struct.unpack(fmt, string)

Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The result is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (len(string) must equal calcsize(fmt)).

Because struct.pack is define as struct.pack(fmt, v1, v2, ...). It accept a non-keyworded argument list (v1, v2, ..., aka *args), so struct.unpack need return a list like object, that's why tuple.

It would be easy to understand if you consider pack as

x = struct.pack(fmt, *args)
args = struct.unpack(fmt, x)  # return *args

Example:

>>> x = struct.pack(">i", 1)
>>> struct.unpack(">i", x)
(1,)
>>> x = struct.pack(">iii", 1, 2, 3)
>>> struct.unpack(">iii", x)
(1, 2, 3)