Sequences are an ordered collection that may contain duplicate elements. This is quite the opposite from Python sets, which is an unordered collection that does not contain duplicate elements.
There are six sequence types - str, bytes, bytearray, range, tuple and list. We have already seen the str primitive data type earlier. All sequences are immutable except for bytearray and lists.
Since sequences are ordered, you may reference them by indices. Recall splicing, which we used for strings. Suppose we have a sequence
s. We may pull a subsequence with the following notations.
Bytes and bytearrays are used to store raw data storing bytes (numbers 0 to 255). Bytearrays are mutable, but bytes are not.
To construct a bytes sequences, use either the
bytes() command. The
b followed by a string converts each character to its ASCII equivalent.
>>> testBytes = bytes(b'hello') >>> testBytes 101 >>> testBytes[1:4] b'ell' >>> testBytes[1:] Traceback (most recent call last): File "<stdin>", line 1, in <modul>e TypeError: 'bytes' object does not support item assignment
Note that for the first call, we have 101, which is the ASCII equivalent of the letter 'e', which is what we have here. For the second example, we call a spliced region and get back a bytes sequence. The last example shows the immutable nature of bytes.
>>> testBytearray = bytearray(b'hello') >>> testBytearray[1:] = b'i' >>> testBytearray bytearray(b('hi'))
In this example, we can see that our
bytearray is mutable.
There are a set of sequence operations that can be used across all the types of sequences. For an element
x in sequence
x in s
xexists in the sequence.
x not in s
xdoes not exist in the sequence.
s + t
2 * s
Let's now move onto the more interesting sequences - Ranges, Tuples and Lists.
This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python.$ Check price
Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.$ Check price