Sequences are a big part of our everyday life. For instance, you might remember that your car is the fourth one in a line (a sequence) in a parking lot. Or you might have a to-do list (a sequence) of tasks for the afternoon. Teaching a child the letters in a word is also dealing with a sequence.
In simple terms, a sequence is just an ordered list of items. Here are some real-world examples of sequences:
- Stock prices listed one after another on a stock ticker.
- Exam scores listed from the first test to the final exam.
- Scientific measurements, like electrical current readings taken over time.
- A long list of names.
- A series of text messages from a friend stored on your phone.
No matter what data each item in the sequence contains, you can process the sequence in the same way: by referring to individual items or subsequences, and by looping through it. Programs often store sequences of data because this data typically appears together in real life, and it needs to be processed together to make sense of it.
Some reasons sequences are useful in software include:
- The sequence data often describes the same thing, event, or process.
- Software solves real-world problems by processing real-world information.
- Real-world information often comes in sequences, so we need to capture and process it in a program to get new, useful information.
In Python, a string is simply a sequence of characters. This means that every character in a string is also a string.
For example, if you type the following in the Python interactive shell:
|
This command does two things:
- Selects the first character ('h') in the string "help".
- Passes it into the built-in type function to print its data type.
The result <class 'str'> shows that each character in a string is also considered a string in Python.
This means processing a string is like processing any other sequence. The same techniques for accessing and modifying elements apply to strings, but the way you format the contents is unique to strings.