๐ŸŒ
Real Python
realpython.com โ€บ python-sequences
Python Sequences: A Comprehensive Guide โ€“ Real Python
March 18, 2026 - Another special method thatโ€™s included in the abstract base class Sequence is .__reversed__(). This method defines how a sequence can be reversed, and itโ€™s called by functions such as the built-in reversed(). Note: The .__contains__() and .__reversed__() special methods arenโ€™t necessary for an object to be a container and reversible. The .__getitem__() special method does a lot of heavy lifting, and Python will fall back onto this method to determine whether an item is a member of a data structure or to reverse the sequence.
๐ŸŒ
TechVidvan
techvidvan.com โ€บ tutorials โ€บ python-sequences
Python Sequences - Types, Operations, and Functions - TechVidvan
January 13, 2020 - The bytes() function in Python is used to return an immutable bytes sequence.
People also ask

What are the different types of sequences in Python?
Python provides several sequence types, including lists, tuples, and strings. Lists are mutable, indexed collections of objects. Tuples are immutable, indexed collections. Strings are immutable sequences of characters.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ python sequence
Python Sequence: Explained & Examples | StudySmarter
How can I iterate over a Python sequence?
You can iterate over a Python sequence using a `for` loop, which will process each element in the sequence in order. Alternatively, use list comprehensions for concise inline iteration, or the `map()` function for applying a function to all sequence items. Use `enumerate()` to access both index and value.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ python sequence
Python Sequence: Explained & Examples | StudySmarter
How can I modify elements in a Python sequence?
To modify elements in a Python sequence, you can directly assign new values to the elements using their indices if the sequence type is mutable, such as a list. Use the syntax `sequence[index] = new_value`. Immutable sequences like tuples or strings require you to convert them to a mutable type, modify, and then convert back if needed.
๐ŸŒ
studysmarter.co.uk
studysmarter.co.uk โ€บ python sequence
Python Sequence: Explained & Examples | StudySmarter
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ python-sequence
Python Sequence and Collections - Operations, Functions, Methods - DataFlair
April 21, 2026 - In Python, the umbrella term sequence covers any ordered series that supports length, slicing, and iterationโ€”lists, tuples, strings, and ranges all qualify. A collection is broader, meaning any container that groups objects, ordered or not, ...
๐ŸŒ
Art of Problem Solving
artofproblemsolving.com โ€บ wiki โ€บ index.php โ€บ Sequence_(Python)
Sequence (Python) - AoPS Wiki
mySeq[i] will return the i'th character of mySeq. Sequences in Python are zero-indexed, so the first element has index 0, the second has index 1, and so on.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ advanced python โ€บ python sequences
Python Sequences
March 27, 2025 - So the first element is s[0] and the second element is s[1]. If the sequence s has n items, the last item is s[n-1]. Python has the following built-in sequence types: lists, bytearrays, strings, tuples, range, and bytes.
๐ŸŒ
Patrickwalls
patrickwalls.github.io โ€บ mathematicalpython โ€บ python โ€บ sequences
Sequences - Mathematical Python
Create a range object with the built-in function range(). The parameters a, b and step in range(a,b,step) are integers and the function creates an object which represents the sequence of integers from a to b (exclusively) incremented by step.
๐ŸŒ
The Python Coding Stack
thepythoncodingstack.com โ€บ the python coding stack โ€บ sequences in python (data structure categories #2)
Sequences in Python (Data Structure Categories #2)
June 25, 2024 - In the first article in the series, we discussed how an iterable is an object that can return its elements one at a time. With a sequence, we're going further. You can fetch an item based on its position in the sequence.
๐ŸŒ
Medium
pythonflood.com โ€บ python-sequences-weaving-the-story-of-order-and-logic-23dff398f83e
Python Sequences - Weaving the Story of Order and Logic. | by Rinu Gour | PythonFlood
July 11, 2023 - Sequences are iterable, meaning you can loop over the elements in a sequence one by one. Python provides several built-in functions to manipulate sequences, such as indexing, slicing, concatenation, and sorting.
Find elsewhere
๐ŸŒ
StudySmarter
studysmarter.co.uk โ€บ python sequence
Python Sequence: Explained & Examples | StudySmarter
The range() function creates a sequence of numbers, commonly used for performing tasks with loops, allowing iteration through elements based on the start, stop, and step arguments provided. ... The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, ...
๐ŸŒ
Python
docs.python.org โ€บ 2.0 โ€บ lib โ€บ typesseq.html
2.1.5 Sequence Types
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted, use 0. If j is omitted, use len(s).
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ make-a-sequence
How to make a sequence - Python Morsels
April 3, 2023 - Some Python utilities will actually check whether an object is iterable by looking for the presence of a __iter__ method. Lastly, we need a __len__ method in order to make our objects work with the built-in len function: class Fibonacci: def __init__(self, n=100): self.n = n def __len__(self): return self.n ... Now instances of our class can work with the len function: ... Mutable sequences need a lot more than immutable ones.
๐ŸŒ
Composingprograms
composingprograms.com โ€บ pages โ€บ 23-sequences.html
2.3 Sequences
The first function selects the value 2 and returns it, which will also be returned from getitem_link. This example demonstrates a common pattern of computation with linked lists, where each step in an iteration operates on an increasingly shorter suffix of the original list. This incremental processing to find the length and elements of a linked list does take some time to compute. Python's built-in sequence types are implemented in a different way that does not have a large cost for computing the length of a sequence or retrieving its elements.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ sequence
Sequences in Python - Python Morsels
June 10, 2026 - Sequences are iterables that have a length. Sequences are ordered collections (they maintain the order of their contents). The most common sequences built-in to Python are string, tuple, and list.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ builtins โ€บ stdtypes.html
Built-in Types โ€” Python 3.14.7 documentation
Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method: ... This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state). sort() accepts two arguments that can only be passed by keyword (keyword-only arguments): key specifies a function ...
๐ŸŒ
NxtWave
ccbp.in โ€บ blog โ€บ articles โ€บ sequence-in-python
Sequence in Python: Types, Methods & Examples
In Python, sequences are ordered collections of items, which can include strings, lists, tuples, byte sequences, byte arrays, and range objects. This combination enables you to perform different operations to work with sequences.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ c-api โ€บ sequence.html
Sequence Protocol โ€” Python 3.14.6 documentation
Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression o[i1:i2]. int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)ยถ ยท Part of the Stable ABI. Assign object v to the ith element of o. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o[i] = v. This function does not โ€œstealโ€ a reference to v.
Top answer
1 of 3
18

Brief introduction to typing in Python

Skip ahead if you know what structural typing, nominal typing and duck typing are.

I think much of the confusion arises from the fact that typing was a provisional module between versions 3.5 and 3.6. And was still subject to change between versions 3.7 and 3.8. This means there has been a lot of flux in how Python has sought to deal with typing through type annotations.

It also doesn't help that python is both duck-typed and nominally typed. That is, when accessing an attribute of an object, Python is duck-typed. The object will only be checked to see if it has an attribute at runtime, and only when immediately requested. However, Python also has nominal typing features. Nominal typing is where one type is declared to be a subclass of another. This can be through inheritance, or with the register() method of ABCMeta.

typing originally introduced its types using the idea of nominal typing. As of 3.8 it is trying to allow for the more pythonic structural typing. Structural typing is related to duck-typing, except that it is taken into consideration at "compile time" rather than runtime. For instance, when a linter is trying to detect possible type errors -- such as if you were to pass a dict to a function that only accepts sequences like tuples or list. With structural typing, a class B should be considered a subtype of A if it implements the all the methods of A, regardless of whether it has been declared to be a subtype of A (as in nominal typing).

Answer

sequences (little s) are a duck type. A sequence is any ordered collection of objects that provides random access to its members. Specifically, if it defines __len__ and __getitem__ and uses integer indices between 0 and n-1 then it is a sequence. A Sequence (big s) is a nominal type. That is, to be a Sequence, a class must be declared as such, either by inheriting from Sequence or being registered as a subclass.

A numpy array is a sequence, but it is not a Sequence as it is not registered as a subclass of Sequence. Nor should it be, as it does not implement the full interface promised by Sequence (things like count() and index() are missing).

It sounds like you want is a structured type for a sequence (small s). As of 3.8 this is possible by using protocols. Protocols define a set of methods which a class must implement to be considered a subclass of the protocol (a la structural typing).

from typing import Protocol
import numpy as np

class MySequence(Protocol):
    def __getitem__(self, index):
        raise NotImplementedError
    def __len__(self):
        raise NotImplementedError
    def __contains__(self, item):
        raise NotImplementedError
    def __iter__(self):
        raise NotImplementedError

def f(s: MySequence):
    for i in range(len(s)):
        print(s[i], end=' ')
    print('end')

f([1, 2, 3, 4]) # should be fine
arr: np.ndarray = np.arange(5)
f(arr) # also fine
f({}) # might be considered fine! Depends on your type checker

Protocols are fairly new, so not all IDEs/type checkers might support them yet. The IDE I use, PyCharm, does. It doesn't like f({}), but it is happy to consider a numpy array a Sequence (big S) though (perhaps not ideal). You can enable runtime checking of protocols by using the runtime_checkable decorator of typing. Be warned, all this does is individually check that each of the Protocols methods can be found on the given object/class. As a result, it can become quite expensive if your protocol has a lot of methods.

2 of 3
1

I think the most practical way to define a sequence in Python is 'A container that supports indexing with integers'.

The Wikipedia definition also holds:

a sequence is an enumerated collection of objects in which repetitions are allowed and order does matter.

To validate if an object is a sequence, I would emulate the logic from the Sequence Protocol:

hasattr(test_obj, "__getitem__") and not isinstance(test_obj, collections.abc.Mapping) 
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ python-in-a โ€บ 0596100469 โ€บ ch04s06.html
Sequence Operations - Python in a Nutshell, 2nd Edition [Book]
July 14, 2006 - Sequence OperationsPython supports a variety of operations applicable to all sequences, including strings, lists, and tuples. Some sequence operations apply to all containers... - Selection from Python in a Nutshell, 2nd Edition [Book]
Author: Alex Martelli
Published: 2006
Pages: 734
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ glossary โ€บ sequence
sequence | Python Glossary โ€“ Real Python
Sequences are fundamental in Python ... repetition, and membership testing. You can also use built-in functions like len(), min(), and max() to perform ......
๐ŸŒ
Wikibooks
en.wikibooks.org โ€บ wiki โ€บ Python_Programming โ€บ Sequences
Python Programming/Sequences - Wikibooks, open books for an open world
But in Python, the colon : allows the square brackets to take two numbers. For any sequence which only uses numeric indexes, this will return the portion which is between the specified indexes.