Why operations between dict views return a set and not a frozenset?

Marco Sulla Marco.Sulla.Python at gmail.com
Wed Jan 5 08:04:48 EST 2022


On Wed, 5 Jan 2022 at 00:54, Chris Angelico <rosuav at gmail.com> wrote:
> That's because a tuple is the correct data type when returning two
> distinct items. It's not a list that has two elements in it; it's a
> tuple of (key, value). Immutability is irrelevant.

Immutability is irrelevant, speed no. A tuple is faster than a list
and more compact. Also frozenset is faster than set. Indeed CPython
optimises internally a

for x in {1, 2, 3}

transforming the set in a frozenset for a matter of speed. That's why
tuple is usually preferred. I expected the same for frozenset

> Got any examples of variable-length sequences?

function positional args are tuples, for example.

> Usually a tuple is a
> structure, not just a sequence.

....eh? Are you talking about the underlying C code?

> If something is just returning a
> sequence, it'll most often return a dedicated sequence type (like
> range in Py3) or a list (like lots of things in Py2).

Python 2 is now obsolete, I don't think is relevant for the discussion.

About your sentence, yes, usually a dedicated view, sequence or
generator is returned, but tuples too are really much used. A list is
returned very sporadically, for what I remember.


More information about the Python-list mailing list