Programming Search⌘K

Conceptcore

Sequence

Also called sequence type, ordered collection, sequenced collection, Sequence ABC, SequenceContainer, lazy sequence, iter.Seq, IEnumerable, iterable.

A sequence is a set of items in a fixed order, where one value can appear more than once. In code the word names indexed types, ordered collections and lazy streams of items.

Applies to
core-languages

Idea

A sequence is the general idea behind arrays, lists, strings and streams: items that come one after another. Wikipedia gives the mathematical definition: "a sequence is a collection of objects possibly with repetition, that come in a specified order". It adds: "Unlike a set, the same elements can appear multiple times at different positions in a sequence, and unlike a set, the order does matter"1. So (1, 2, 1) is a sequence of three items, and it is not the same sequence as (1, 1, 2).

In programming, the word has three common meanings:

  • an indexed sequence, which has a length and an item at each position from 0 to the length minus 1, such as an array, a list, a tuple or a string;
  • an ordered collection, which has a first item and a last item and can be read in order and in reverse, such as a list, a deque or an ordered set;
  • a lazy sequence or stream, which gives one item at a time when a loop asks for it. It can be infinite, and it can have no length and no index.

Wikipedia connects these words: "In computer science, finite sequences are called lists. Potentially infinite sequences are called streams. Finite sequences of characters or digits are called strings"1.

from collections.abc import Sequence
from itertools import count, islice

# A sequence has a length and an item for each index from 0 to length - 1.
# This class stores no items. It computes item i when the program asks for it.
class Squares(Sequence):
    def __init__(self, n):
        self.n = n

    def __len__(self):
        return self.n

    def __getitem__(self, i):
        if isinstance(i, slice):
            return [self[j] for j in range(*i.indices(self.n))]
        if i < 0:
            i += self.n
        if not 0 <= i < self.n:
            raise IndexError(i)
        return i * i

sq = Squares(6)
# The Sequence base class builds in, iteration, reversed, index and count from the two methods.
print(len(sq), sq[2], sq[-1], sq[1:4])
print(list(sq), 16 in sq, sq.index(9), list(reversed(sq)))

# A lazy sequence can be infinite. It has an order but no length.
evens = (2 * k for k in count())
print(list(islice(evens, 5)), next(evens))
Output
6 4 25 [1, 4, 9]
[0, 1, 4, 9, 16, 25] True 3 [25, 16, 9, 4, 1, 0]
[0, 2, 4, 6, 8] 10

Squares stores no items, but it is a full indexed sequence, because it has a length and an item for each index. The Python base class gives it in, iteration, reversed, index and count for free. The generator evens is a lazy sequence: it has an order, but it never ends, so the program takes 5 items with islice, and the next item is 10.

How it works

Indexed sequences. An indexed sequence needs two operations: the length and the item at a position. Python defines a sequence as "An iterable which supports efficient element access using integer indices via the getitem() special method and defines a len() method that returns the length of the sequence"2. The abstract base class Sequence asks for __getitem__ and __len__ and gives the mixin methods "contains, iter, reversed, index, and count"3. MutableSequence adds the methods that change the items, such as insert, append and pop3. Every operation of an indexed sequence can be built from these few, so code that uses only them works on arrays, lists, strings, ranges and computed sequences.

A type can have a length and an index operator and still not be a sequence. Python notes that a dict "also supports getitem() and len(), but is considered a mapping rather than a sequence because the lookups use arbitrary hashable keys"2. In a sequence, the keys are the positions.

Ordered collections. Some collections have an order but no fast index. Java added an interface for them in Java 21. JEP 431 says: "Java’s collections framework lacks a collection type that represents a sequence of elements with a defined encounter order"4. The new interface SequencedCollection is "A collection that has a well-defined encounter order, that supports operations at both ends, and that is reversible"5. List, Deque and LinkedHashSet implement it, but HashSet does not, because it has no defined order4.

Sequence containers. C++ uses the word for a group of container types. "A SequenceContainer is a Container that stores objects of the same type in a linear arrangement"6. std::vector, std::deque, std::list and std::forward_list meet these requirements, so one template can call insert, front and back on any of them. The cppreference table lists the tradeoffs, for example std::vector has "Fast access, contiguous storage" and "Mostly inefficient insertions/deletions"6.

Lazy sequences. A lazy sequence does not store its items. It computes each item when the consumer asks for the next one. Kotlin explains the difference: "Unlike collections, sequences don't contain elements, they produce them while iterating"7. Each step of a pipeline over a collection makes a whole intermediate collection, but "multistep processing of sequences is executed lazily when possible: actual computing happens only when the result of the whole processing chain is requested"7. Rust iterators work in the same way: "Iterators (and iterator adapters) are lazy. This means that just creating an iterator doesn’t do a whole lot. Nothing really happens until you call next"8. See laziness and iterators.

A lazy sequence can be infinite. Rust gives an example: "an open-ended range is an infinite iterator", and "It is common to use the take iterator adapter to turn an infinite iterator into a finite one"8. JavaScript describes its iterator protocol as "a standard way to produce a sequence of values (either finite or infinite)"9.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeTypeScript uses the JavaScript iterable protocol with types. Iterable<T>, Iterator<T> and Generator<T> describe sequences, and ArrayLike<T> describes objects with length and indices. No example file exists.
GoStandard library
RustNative
KotlinStandard libraryList<T> is the ordered collection, and Sequence<T> is a lazy sequence that runs its steps item by item. sequenceOf, generateSequence and asSequence make sequences. No example file exists because kotlinc is not installed.
SQLIdiomA table has no order of its own. ORDER BY gives the rows an order, and CREATE SEQUENCE makes a generator of numbers, not a collection. Array types exist in PostgreSQL.
BashNativeAn indexed array is the only sequence type. A for loop over "${a[@]}" visits the items in order, and seq or brace expansion makes a sequence of numbers. No example file exists.
PowerShellNativeArrays and the .NET collections are sequences, and the pipeline sends the items of a sequence one at a time. 1..5 makes an array of numbers. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. The order of elements in a list is document order, not a data type.
CSSDoes not applyCSS style rules have no sequence values. Counters number elements, but they are not data.
Regular expressionsDoes not applyA regular expression matches text. It has no sequence values.
Language Verdict Mechanism
Python native list, tuple, str, bytes and range; the Sequence and MutableSequence base classes; generators for lazy sequences
JavaScript native the iterable protocol (Symbol.iterator) for arrays, strings, Map, Set and generators
TypeScript native the JavaScript protocols with the types Iterable<T>, ArrayLike<T> and ReadonlyArray<T>
Java stdlib SequencedCollection (Java 21) for List, Deque and ordered sets; Stream for lazy sequences
Kotlin stdlib List<T> for indexed sequences; Sequence<T> for lazy ones, made with sequenceOf and generateSequence
C# stdlib IEnumerable<T> with yield return and LINQ; IReadOnlyList<T> and IList<T> for indexed sequences
Go stdlib slices for indexed sequences; iter.Seq and iter.Seq2 functions with range over a function (Go 1.23)
Rust stdlib slices [T] for indexed sequences; the Iterator trait for lazy sequences
C idiom a pointer and a length; a lazy sequence is a struct with its state and a next function
C++ stdlib the SequenceContainer types; ranges and views (C++20) for lazy sequences
Bash native indexed arrays, the words of "$@" and the output of seq
PowerShell native arrays and the pipeline, which passes one object at a time
SQL idiom rows in the order of ORDER BY; CREATE SEQUENCE makes a number generator, which is a different thing
Regex n/a a pattern matches a sequence of characters but has no sequence values
HTML n/a markup; the order of elements in a document is a sequence, but HTML has no data type for it
CSS n/a style rules have no sequences

The languages split the three meanings in different ways. Python, Java and C# have one interface for each meaning. Go and Rust use a slice for the indexed sequence and a separate type for the lazy one. In Go, "An iterator is a function that passes successive elements of a sequence to a callback function, conventionally named yield"10. C# makes lazy sequences with yield return, and its base interface IEnumerable<T> "Exposes the enumerator, which supports a simple iteration over a collection of a specified type"11. In JavaScript, "The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct"9.

SQL uses the word for something else. In PostgreSQL, "CREATE SEQUENCE creates a new sequence number generator"12, an object that gives the next number of a counter, often for a key column. It does not store a sequence of values.

The example files show these forms. Python shows which built-in types are sequences, the common operations on lists, tuples and ranges, and a generator that gives its items once. JavaScript defines an iterable object, an infinite generator and the iterables of the language. Java shows one method for a list, a deque and a LinkedHashSet through SequencedCollection, a reversed view and an infinite Stream. C# shows a lazy yield return sequence, a deferred LINQ query that sees later changes, and ToList. Go writes an iter.Seq for Fibonacci numbers, stops it with break, and uses slices.Values, slices.Backward and maps.Keys. Rust shows next, a lazy map that runs only when the program collects, an infinite range and successors. C writes a lazy sequence as a struct and a next function. C++ uses one template on three containers, then a lazy pipeline of views.

PythonGitHub
from collections.abc import MutableSequence, Sequence
from itertools import islice

# list, tuple, str, bytes and range are sequences: they have len and integer indices.
for value in ([1, 2], (1, 2), "ab", b"ab", range(2)):
    print(type(value).__name__, isinstance(value, Sequence), isinstance(value, MutableSequence))

# A dict also has len and [], but its keys are not positions, so it is not a sequence.
# A set has len but no order. A generator has an order but no len and no index.
gen = (x for x in range(3))
print(isinstance({}, Sequence), isinstance(set(), Sequence), isinstance(gen, Sequence))

# The common sequence operations work on every built-in sequence.
for s in ([3, 1, 3], (3, 1, 3), range(3, 0, -1)):
    print(type(s).__name__, len(s), s[0], s[-1], s.index(1), s.count(3), min(s), 1 in s)

# A str is a sequence of strings of length 1, and in searches for a substring.
print("abc".index("b"), "bc" in "abc", "abc"[::-1])

# A generator gives its items once. A second pass finds nothing.
squares = (n * n for n in range(4))
print(list(squares), list(squares))
print(list(islice(range(10**18), 3)), len(range(10**18)))
Output
list True True
tuple True False
str True False
bytes True False
range True False
False False False
list 3 3 3 1 2 1 True
tuple 3 3 3 1 2 1 True
range 3 3 1 2 1 1 True
1 True cba
[0, 1, 4, 9] []
[0, 1, 2] 1000000000000000000
  • Verdict: native. list, tuple, str, bytes and range are Sequence, and only list is a MutableSequence. A dict, a set and a generator are not sequences. len, indexing, index, count, min and in work the same on every built-in sequence. A generator gives its items once, and range(10**18) has a length without storing its items.
#include <deque>
#include <iostream>
#include <list>
#include <ranges>
#include <string>
#include <vector>

// One template for every sequence container: they all have insert, front, back and begin.
template <typename Seq>
std::string demo(Seq s) {
    s.insert(s.begin(), 0);
    s.push_back(9);
    std::string out;
    for (int x : s) {
        out += std::to_string(x);
    }
    return out + " front " + std::to_string(s.front()) + " back " + std::to_string(s.back());
}

int main() {
    std::cout << demo(std::vector<int>{1, 2}) << '\n';
    std::cout << demo(std::deque<int>{1, 2}) << '\n';
    std::cout << demo(std::list<int>{1, 2}) << '\n';

    // A range view is a lazy sequence. iota without an end is infinite; take makes it finite.
    auto odd_squares = std::views::iota(1) | std::views::transform([](int n) { return n * n; }) |
                       std::views::filter([](int n) { return n % 2 == 1; }) | std::views::take(4);
    for (int n : odd_squares) {
        std::cout << n << ' ';
    }
    std::cout << '\n';

    // Views compose without copies. reverse and drop work on the vector in place.
    std::vector<int> v{1, 2, 3, 4, 5};
    for (int n : v | std::views::reverse | std::views::drop(1)) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
}
Output
0129 front 0 back 9
0129 front 0 back 9
0129 front 0 back 9
1 9 25 49
4 3 2 1
  • Verdict: stdlib. One template works on vector, deque and list, because all three are sequence containers with begin, end, front and back. The ranges views iota, transform, filter and take make a lazy pipeline. reverse and drop are views over a vector, so they copy nothing.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
import java.util.stream.Stream;

public class Main {
    // One method for every collection with a defined order: lists, deques and ordered sets.
    static String ends(SequencedCollection<String> c) {
        return c.getFirst() + ".." + c.getLast() + " " + c.reversed();
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("a", "b", "c"));
        Deque<String> deque = new ArrayDeque<>(List.of("x", "y"));
        LinkedHashSet<String> set = new LinkedHashSet<>(List.of("k", "j", "k", "i"));
        System.out.println(ends(list) + " | " + ends(deque) + " | " + ends(set));

        // reversed() is a view: a change through it changes the list.
        List<String> back = list.reversed();
        back.addFirst("z");
        System.out.println(list + " " + back);

        // HashSet has no defined order, so it is not a SequencedCollection.
        System.out.println((Object) new HashSet<String>() instanceof SequencedCollection);

        // A Stream is a lazy sequence. iterate gives an infinite stream, and limit makes it finite.
        System.out.println(Stream.iterate(1, n -> n * 2).limit(6).toList());
    }
}
Output
a..c [c, b, a] | x..y [y, x] | k..i [i, j, k]
[a, b, c, z] [z, c, b, a]
false
[1, 2, 4, 8, 16, 32]
  • Verdict: stdlib. Since Java 21, one method takes any SequencedCollection: a list, a deque or a LinkedHashSet. reversed() is a view, so addFirst through it adds to the end of the list. A HashSet has no defined order and is not a SequencedCollection. Stream.iterate gives an infinite lazy stream, and limit makes it finite.
#include <stdbool.h>
#include <stdio.h>

/* C has no sequence type. A lazy sequence is a struct that holds the state and a next function. */
typedef struct {
    unsigned long a, b;
} Fib;

static bool fib_next(Fib *f, unsigned long *out) {
    *out = f->a;
    unsigned long next = f->a + f->b;
    if (next < f->b) {
        return false; /* the next sum would wrap around, so the sequence ends */
    }
    f->a = f->b;
    f->b = next;
    return true;
}

/* An indexed sequence is an array and a length. Any function that takes both can read it. */
static int sum(const int *items, size_t len) {
    int total = 0;
    for (size_t i = 0; i < len; i++) {
        total += items[i];
    }
    return total;
}

int main(void) {
    Fib f = {0, 1};
    unsigned long x;
    for (int i = 0; i < 10 && fib_next(&f, &x); i++) {
        printf("%lu ", x);
    }
    printf("\n");

    /* The same state type can run to its natural end. */
    Fib all = {0, 1};
    int count = 0;
    while (fib_next(&all, &x)) {
        count++;
    }
    printf("%d terms fit before the sum overflows\n", count);

    int data[] = {4, 8, 15, 16, 23, 42};
    printf("%d %d\n", sum(data, 6), sum(data + 2, 3));
    return 0;
}
Output
0 1 1 2 3 5 8 13 21 34
92 terms fit before the sum overflows
108 54
  • Verdict: idiom. C has no sequence type. A struct that keeps state and a next function give a sequence one item at a time, and the program stops when the next sum would overflow. A function that takes a pointer and a length works on any array of that type.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static int produced = 0;

    // yield return makes a lazy IEnumerable<T>. The body runs only while a loop asks for items.
    static IEnumerable<int> Naturals()
    {
        for (int n = 0; ; n++)
        {
            produced++;
            yield return n;
        }
    }

    static void Main()
    {
        var firstSquares = Naturals().Select(n => n * n).Take(5);
        Console.WriteLine($"produced before: {produced}");
        Console.WriteLine($"{string.Join(",", firstSquares)} produced after: {produced}");

        // A LINQ query is deferred: it reads the list each time it runs, so it sees later changes.
        var list = new List<int> { 1, 2, 3 };
        IEnumerable<int> big = list.Where(x => x > 1);
        list.Add(10);
        Console.WriteLine($"{string.Join(",", big)} {big.Count()}");

        // ToList runs the query once and keeps the result.
        List<int> snapshot = big.ToList();
        list.Add(20);
        Console.WriteLine($"{snapshot.Count} {big.Count()}");

        // Arrays, lists and strings are all IEnumerable<T>. IReadOnlyList<T> adds Count and an indexer.
        IReadOnlyList<char> chars = "abc".ToList();
        IEnumerable<int>[] seqs = { new[] { 1, 2 }, new List<int> { 3 }, Enumerable.Range(4, 2) };
        Console.WriteLine($"{chars.Count} {chars[^1]} {string.Join(",", seqs.SelectMany(s => s))}");
    }
}
Output
produced before: 0
0,1,4,9,16 produced after: 5
2,3,10 3
3 4
3 c 1,2,3,4,5
  • Verdict: native. A method with yield return gives an IEnumerable that runs only when a loop asks for items, so the counter is 0 until Join reads the query. A LINQ query is deferred, so it sees an item added after it was made, and ToList takes a snapshot. ToList on a string gives a List, which is an IReadOnlyList. SelectMany joins an array, a list and a range into one sequence.
JavaScriptGitHub
// Any object with a [Symbol.iterator] method is a sequence for for...of, spread and Array.from.
const countdown = {
  from: 3,
  [Symbol.iterator]() {
    let n = this.from;
    return { next: () => (n > 0 ? { value: n--, done: false } : { value: undefined, done: true }) };
  },
};
console.log([...countdown], Array.from(countdown, (x) => x * 10));

// A generator makes a lazy sequence. This one never ends, so the program takes only a few items.
function* naturals() {
  for (let n = 0; ; n++) yield n;
}
const taken = [];
for (const n of naturals()) {
  if (n >= 4) break;
  taken.push(n);
}
console.log(taken);

// Arrays, strings, Maps and Sets are iterable. Plain objects are not.
console.log([..."hé!"], [...new Set([2, 2, 1])], typeof {}[Symbol.iterator]);

// next() gives one item at a time. A generator object is one pass: after it ends, it gives nothing more.
const once = naturals();
console.log(once.next().value, once.next().value);
function* pair() {
  yield 1;
  yield 2;
}
const g = pair();
console.log([...g], [...g], [...pair()]);
Output
[ 3, 2, 1 ] [ 30, 20, 10 ]
[ 0, 1, 2, 3 ]
[ 'h', 'é', '!' ] [ 2, 1 ] undefined
0 1
[ 1, 2 ] [] [ 1, 2 ]
  • Verdict: native. An object with a Symbol.iterator method works with for...of, spread and Array.from. A generator makes a lazy sequence, and break stops an infinite one. Arrays, strings and Sets are iterable, and a plain object is not. A generator object is one pass, so a second spread gives an empty array.
package main

import (
	"fmt"
	"iter"
	"maps"
	"slices"
)

// Fib returns a lazy sequence. It computes each number when the loop asks for it.
func Fib() iter.Seq[int] {
	return func(yield func(int) bool) {
		a, b := 0, 1
		for {
			if !yield(a) {
				return // the loop stopped early
			}
			a, b = b, a+b
		}
	}
}

func main() {
	// range over a function calls it with a yield function. break makes yield return false.
	for n := range Fib() {
		if n > 50 {
			break
		}
		fmt.Print(n, " ")
	}
	fmt.Println()

	// slices.Values turns a slice into a sequence, and slices.Collect turns a finite sequence into a slice.
	words := []string{"b", "a", "c"}
	fmt.Println(slices.Collect(slices.Values(words)), slices.Sorted(slices.Values(words)))

	// Seq2 gives two values per step, such as an index and an item.
	for i, w := range slices.Backward(words) {
		fmt.Print(i, w, " ")
	}
	fmt.Println()

	// A map gives a sequence of keys in no fixed order, so the program sorts them.
	m := map[string]int{"y": 2, "x": 1, "z": 3}
	fmt.Println(slices.Sorted(maps.Keys(m)))
}
Output
0 1 1 2 3 5 8 13 21 34
[b a c] [a b c]
2c 1a 0b
[x y z]
  • Verdict: stdlib. Since Go 1.23, an iter.Seq is a function that a range loop calls, and break stops an infinite sequence. slices.Values, slices.Collect, slices.Sorted and slices.Backward change between slices and sequences. maps.Keys gives the keys of a map as a sequence, in no fixed order, so the program sorts them.
RustGitHub
use std::cell::Cell;

fn main() {
    // An iterator is a sequence that gives one item per call to next.
    let v = vec![10, 20, 30];
    let mut it = v.iter();
    println!("{:?} {:?} {:?} {:?}", it.next(), it.next(), it.next(), it.next());

    // Adapters are lazy: map runs only when something consumes the iterator.
    let calls = Cell::new(0);
    let doubled = v.iter().map(|x| {
        calls.set(calls.get() + 1);
        x * 2
    });
    println!("calls before: {}", calls.get());
    let out: Vec<i32> = doubled.collect();
    println!("{:?} calls after: {}", out, calls.get());

    // 0.. is an infinite sequence. take makes it finite.
    let squares: Vec<u64> = (0..).map(|n: u64| n * n).filter(|n| n % 2 == 1).take(4).collect();
    println!("{:?}", squares);

    // A slice is an indexed sequence. Its iterator can also run backward.
    let s = &v[..];
    println!("{} {} {:?}", s.len(), s[1], s.iter().rev().collect::<Vec<_>>());

    // successors builds a sequence from a first item and a rule for the next one.
    let powers: Vec<u32> = std::iter::successors(Some(1u32), |&p| p.checked_mul(10)).collect();
    println!("{} {:?}", powers.len(), powers.last());
}
Output
Some(10) Some(20) Some(30) None
calls before: 0
[20, 40, 60] calls after: 3
[1, 9, 25, 49]
3 20 [30, 20, 10]
10 Some(1000000000)
  • Verdict: native. next returns Some for each item and then None. map is lazy: the counter stays 0 until collect runs. The open range 0.. is infinite, and take makes it finite. A slice gives an iterator that can go in reverse. successors with checked_mul stops when the next value overflows.
  • Strings. A string is a sequence of characters, bytes or code units. Python strings are sequences of strings of length 1. See string.
  • Tuples. A tuple is a fixed-length sequence, usually with items of different types.
  • Ranges. A range such as range(0, 10, 2) is an indexed sequence that stores only its start, stop and step. In the Python example, len(range(10**18)) takes no memory for the items.
  • Persistent sequences. Haskell's Data.Seq gives "General-purpose finite sequences"13 that are immutable and fast at both ends. "The implementation uses 2-3 finger trees annotated with sizes"13.
  • Streams. Wikipedia uses stream for a sequence that can be infinite1. Java Stream, Kotlin Sequence and Rust iterators are examples.
  • Slices. A slice is a part of an indexed sequence, and in many languages it is a sequence of the same type.

Pitfalls

  • One pass. A generator, an iterator or a Java Stream gives its items once. In the Python and JavaScript examples, a second pass over the same generator finds nothing. Make a list if the code needs the items twice.
  • Deferred work. A lazy query runs when the program reads it, not when the program writes it. In the C# example, a query made before list.Add(10) still sees 10, and it runs again each time the program counts it.
  • Infinite sequences. A call that reads all items, such as list, collect, ToList or count, never ends on an infinite sequence. Take a fixed number of items first.
  • Side effects in lazy steps. A map with a side effect does nothing until something consumes the sequence. In the Rust example, the counter is 0 before collect and 3 after it.
  • Not every ordered type is indexed. in and index on a lazy sequence or a linked list walk the items one by one. Code that takes a general sequence must not assume that item i is one step away.
  • Different meanings of the word. A Python sequence has an index, a Kotlin Sequence is lazy, a Java SequencedCollection has two ends, and an SQL sequence is a counter. Read the definition in each language.

Cost

Kind Item i Length Memory Passes
array or array list constant constant all items many
linked list linear in i constant if stored all items and links many
range constant constant three numbers many
lazy sequence linear in i (compute the items before it) unknown, maybe infinite the state of one step often one

An indexed sequence keeps all its items, so random access is fast and the memory grows with the length. A lazy sequence keeps only its state, so it can handle data that does not fit in memory, and it stops early when the consumer has enough. The cost is per item: each step calls a function, and the sequence cannot go back.

History

The idea comes from mathematics, where a sequence is a function from the natural numbers, or from the first n of them, to a set of values1. Programming languages took the idea in two forms. Arrays and lists, from the 1950s, store finite sequences. Lazy streams came later, in functional languages and then in the generators of Python, the iterators of C# 2.0 with yield return, and the streams of Java 8.

Recent languages added names for the shared interface. Java added SequencedCollection in Java 214, and Go added iter.Seq in Go 1.23. The Go documentation says that the name Seq is pronounced like seek, the first syllable of sequence10.

References

  1. Sequence, Wikipedia, Introduction; Computing; Streams
  2. Glossary, Python documentation, sequence
  3. collections.abc, The Python Standard Library, Collections Abstract Base Classes; Sequence and MutableSequence
  4. JEP 431, Sequenced Collections, Summary; Motivation
  5. Interface SequencedCollection, Java SE 25 API, Interface description
  6. C++ named requirements, SequenceContainer, cppreference.com, Introduction; Usage notes
  7. Sequences, Kotlin documentation, Introduction
  8. Module iter, The Rust Standard Library, Infinity; Laziness
  9. Iteration protocols, MDN Web Docs, The iterable protocol; The iterator protocol
  10. Package iter, Go standard library, Iterators; type Seq
  11. IEnumerable<T> Interface, .NET API reference, Definition
  12. CREATE SEQUENCE, PostgreSQL documentation, Description
  13. Data.Sequence, the containers package, Hackage, Description; Implementation

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/WAYDS7/text.yaml