Two common meanings
In computer science, the word sequence can mean either of two things. Context usually makes clear which one is meant.
- A control structure. A sequence is a group of instructions that run one after another, without condition checks or repetition. This is the sense used in the term sequencing. For the full idea, see what is sequencing in computer science.
- An ordered collection. A sequence is a collection of items in which each item has a position. You can refer to the first, second, or last item, and the order is part of the data.
Sequence as an ordered collection
Python has several built-in sequence types, including lists, tuples, and strings. Each one stores items in a fixed order, and you can read an item by its index. Python indexes start at 0:
letters = ["a", "b", "c"]
print(letters[0]) # prints a
word = "cat"
print(word[1]) # prints a
The first item in the list is "a", and the item at index 1 in the string "cat" is also "a". The index counts positions, not values.
Sequence in mathematics
In mathematics, a sequence is an ordered list of numbers, such as 2, 4, 6, 8. Programmers borrow the idea, so a program might store a list of values that are meant to be read in order.
Telling the two meanings apart
Surrounding words are usually the best guide:
- Words such as statement, execution, order of steps, or control flow point to the control structure meaning.
- Words such as index, element, length, or list point to the ordered collection meaning.
Some discussions use both meanings at once. A program might run a sequence of statements that loops over a sequence of values.
Where the two meanings meet
Both meanings depend on order. A sequence of instructions runs in order, and a sequence of values keeps its items in order. Arrays are a common way to store values in order in memory. For how arrays fit into this picture, see is an array a data structure.
Summary
- Sequence can mean steps run in order, or an ordered collection of items.
- Surrounding words usually show which meaning is intended.
- In Python, lists, tuples, and strings are sequence types, and their items are read by index.