Intrastellar Explorer
Intrastellar Explorer

Reputation: 2411

Python type hinting: when to use MutableSequence vs List

I have been reading about typing.Sequence and typing.MutableSequence. There isn't a ton of "light reading" out there on either of the two, everything goes straight into details.

From this answer to Can you specify variance in a Python type annotation?

Sequence is the read-only version of List

So that leads me to wonder, what is the difference between MutableSequence, and just a plain List?


More Details

The best source I could find was the The standard type hierarchy section of the Python Data model.

From reading the section Mutable sequences, it seems like MutableSequence might be a "parent" of List?

In other words, one can use them interchangeably, just MutableSequence is a bit less restrictive?

Upvotes: 5

Views: 3755

Answers (1)

user2357112
user2357112

Reputation: 280973

MutableSequence represents arbitrary mutable sequences. For example, an instance of array.array satisfies MutableSequence.

List is specifically just lists. If an object is not a list, it doesn't satisfy List.

Use MutableSequence when you want to express "mutable sequence". Use List when you want to express "list".

Upvotes: 8

Related Questions