Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

In Python, a sequence is a collection of objects ordered by their position.

In Python, there are three basic sequences,


which are lists, tuples, and so-called "range objects".
But Python also has additional sequence types
for representing things like strings.
The crucial aspect about sequences is that any sequence data type will
support the common sequence operations.
But, in addition, these different types will
have their own methods available for performing specific operations.
Sequences are called "sequences" because the objects
that they contain form a sequence.
So let's look at this as a diagram.
Imagine that this is our sequence, and we
have a few different objects in our sequence here-- triangles, squares,
and circles, in this example.
The first, fundamental aspect to understand about sequences
is that indexing starts at 0.
So if we call this sequence "s", we would
access the first element in our sequence by typing "s"
and, in brackets, putting its location, which is 0.
This object here in the second position would be addressed and accessed
as s[1], and so on.
This would be s 2, 3, and 4.
Another way to access objects within the sequence
is not to count from left to right, but from right to left.
So we can access sequences either by giving a positive index, which
is counting a location from the left to right,
or we can use a negative index, which is counting positions from right to left.
In that case, we have to use the negative 1 for the very
last object in our sequence.
Correspondingly, minus 2 would correspond
to the second to last object, and so on.
Sequences also support an operation called "slicing."
So let's take a look at that now.
If we, again, have our sequence "s". To access
a specific unit, specific object, we would just
use the location-- for example, 2, in this case.
However, if we wanted to extract multiple objects in the sequence,
we can do the following.
We can say s bracket, say, 0, 2.
This first index, the first position is the start position,
and the second position here is to stop position.
Python slices stop before Python reaches the element at the stop location.
This means that if you type "s", and, in brackets, "0 column 2",
Python is going to return a slice to which
consists of the objects in locations 0 and 1,
but it will not return to you the object at location 2.

You might also like