6

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?

5
  • 3
    Sequence is not a read-only version of List. The answer you read was wrong about that. Commented Jun 6, 2020 at 23:23
  • @user2357112supportsMonica from reading Lists (docs.python.org/3.6/library/stdtypes.html#lists), it says "Lists are mutable sequences". So am I correct in my understanding that MutableSequence is a superset of List? Commented Jun 6, 2020 at 23:36
  • 2
    Yes, that is correct. Commented Jun 6, 2020 at 23:37
  • 1
    @IntrastellarExplorer: Depending on how you interpret superset, you may be viewing this backwards; List is a superset of MutableSequence's guaranteed features. MutableSequence is the minimum requirement, but a list can do stuff that not all MutableSequences can do, e.g. list can hold any object, while other mutable sequences like array.array are limited to numeric types in specific ranges. Commented Jun 6, 2020 at 23:47
  • Yes @ShadowRanger good point. I have changed my wording in the question from "superset" to "parent", for clarity. Commented Jun 6, 2020 at 23:55

1 Answer 1

8

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.