PROGRAMMING-CONCEPTS

Sequence: Concept, Behavior, and Examples

A sequence is an ordered collection of elements that can be accessed one by one in a specific order. It defines a fundamental programming idea — that data can be arranged and processed step-by-step, rather than existing as isolated values.

Sequences appear across many languages and data structures. Lists, arrays, tuples, and even strings are all examples of sequences because they preserve order and allow indexed access. This concept forms the backbone of loops, iterations, and most data traversal techniques in programming.


The Concept of Order

Unlike sets or dictionaries, which focus on unique elements or key-value pairs, sequences preserve order. That means each item occupies a predictable position, called an index, and operations like slicing, iteration, and mapping depend on that order.

In essence, a sequence ensures two guarantees:

  1. You can reach any element using its position.
  2. When you traverse it, elements appear in a consistent order.

This predictability is what allows algorithms, loops, and string operations to work consistently across languages.


Sequences Across Programming Languages

In Python, sequences include data types like lists, tuples, ranges, and strings.

cities = ("Paris", "Rome", "Vienna")  # tuple
for city in cities:
    print(city)

In JavaScript and TypeScript, arrays are the main form of sequence, while strings can also be treated as character sequences:

const greeting = "hello";
for (const letter of greeting) {
  console.log(letter);
}

In Swift, arrays and strings both conform to the Sequence protocol, meaning you can iterate over them with for-in loops and use high-level methods like map and filter.

The details differ between languages, but the abstract behavior remains the same — sequences are iterable, ordered, and indexable.


Strings as Sequences

Strings are one of the most overlooked examples of sequences. Each character has a position, and you can access, loop, or slice strings the same way as numeric collections.

word = "coding"
print(word[2])  # 'd'

const word = "coding";
console.log(word[2]); // 'd'

This shows that sequences aren’t limited to numbers or lists — they can represent any data arranged in order, including text, DNA sequences, or binary data streams.


Tuples and Immutable Sequences

Not all sequences are meant to change. Tuples in Python or fixed-size arrays in Swift are immutable — once created, their order and contents remain fixed.

coordinates = (42.1, 19.3)

Immutable sequences are useful for data that should not be modified accidentally, such as configuration values, coordinates, or constant sets of parameters.

Mutable sequences, like Python lists or JavaScript arrays, let you add, remove, or replace elements freely. Both exist because sometimes stability matters more than flexibility.


Iteration and Traversal

The defining operation for any sequence is iteration — going through each element in order. Iteration powers loops, aggregations, and transformations.

Here’s how a loop behaves with a sequence in Python:

numbers = [1, 2, 3]
for n in numbers:
    print(n * 2)

And in JavaScript:

const numbers = [1, 2, 3];
for (const n of numbers) {
  console.log(n * 2);
}

The specific syntax changes between languages, but the logic — visiting each element in sequence — stays constant.


Derived Sequences

Many languages let you generate or transform sequences rather than create them manually. Python’s range() function produces a sequence of numbers without storing each one explicitly:

for i in range(5):
    print(i)

Similarly, JavaScript offers functions that derive new sequences from old ones — map(), filter(), and reduce() all operate on ordered collections, producing new sequences based on logic you define.

These features make programming more declarative: you describe what you want done with the sequence, not how to do it step by step.


Working with Sequence Slices

A slice extracts part of a sequence while preserving order. This is common when processing large datasets or cleaning subsets of text.

In Python:

numbers = [10, 20, 30, 40, 50]
subset = numbers[1:4]  # [20, 30, 40]

In Swift:

let numbers = [10, 20, 30, 40, 50]
let subset = numbers[1...3]

Slicing can be seen as viewing a window into the sequence without altering the original data.


Sequences in Data Processing

Sequences are fundamental in data workflows because they represent collections that can be processed predictably. In machine learning, a dataset is often represented as a sequence of records. In SQL, query results are returned as ordered sequences of rows.

In React, sequences of objects (like user data) are often mapped directly to interface elements:

const users = ["Luna", "Milo", "Eli"];
return (
  <ul>
    {users.map(name => <li key={name}>{name}</li>)}
  </ul>
);

Here, the concept of a sequence connects raw data to visible elements, reinforcing that order and iteration are central ideas across programming domains.


Performance and Memory Considerations

Some sequences, such as Python generators or Swift iterators, don’t store all their elements at once. Instead, they produce items on demand. These are lazy sequences, useful for working with large or infinite data streams.

Generators, for example, yield one value at a time:

def count_up():
    n = 1
    while True:
        yield n
        n += 1

Lazy sequences improve efficiency because they process elements as needed rather than holding everything in memory.


Common Mistakes

Beginners often assume that all collections are sequences, but structures like sets or dictionaries don’t maintain order. Another frequent issue is misusing indexes — especially forgetting that most languages start indexing at zero.

Finally, modifying a sequence while iterating through it can lead to skipped or duplicated elements. The safer approach is to build a new sequence rather than editing one mid-loop.


Summary

A sequence is the abstract idea of ordered data — the guarantee that items appear and can be accessed in a consistent order. Lists, arrays, tuples, strings, and even generators all express this idea differently, but they share the same foundation: order, iteration, and predictability.

While arrays implement this concept in a specific way, sequences represent the broader pattern that gives structure to programming logic itself. Understanding sequences means understanding how data flows — step by step, in order, from one operation to the next.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster