0:01

As we'll see in upcoming lectures, it can be very useful to have sequences of

numbers that represent the indices of strings or lists.

In this lecture, I will introduce the Python built-in function range and we'll

use it for this purpose. In this first example, we will use a for

loop in conjunction with range, to generate and display a sequence of

integers from zero up to and including nine.

So for each number n, and this is where we use range, range will generate that

sequence of numbers, I'm going to pass in the value ten, this is the value of, of

the sequence that we are going up to. I'll print each number in the sequence.

The numbers we see on the screen are integer values from zero to nine.

The starting value produced is by default zero.

The ending value is up to ten. So nine is our ending value.

And the step, or the difference between any two values in the sequence, is by

default, one. Let's look at the help for range.

The help is rather lengthy, but I want to focus on the header.

We can see from this header that there are up to three arguments that we can provide

to the function. The one that we provided in our example

was the stop, the stopping value. We can optionally provide a starting value

for which the default is zero, and we can optionally provide a step if we omit that

then the default as I mentioned and showed in the example is a step of one.

One of the ways that we'll use range is to generate a sequence of numbers that

represent the indices of a string or a list.

So for the string computer science, we'll use range to generate its indices.

Computer science has sixteen characters. So the indices are values zero, one, two,

up to fifteen. Using range we can generate those values.

I could pass sixteen as the argument to range.

But to be more general I can say, go up to the length of the string.

Notice that I'm using I to represent the index of S, so I is short for index.

And the values zero through fifteen are printed.

2:29

But perhaps, we only want the indices starting from index one.

We can use the optional parameter, start, to indicate this.

So I can pass in one for the start index, and then go up to the length of the

string. And when we're, print the value this time,

we see that we go from one up to and including fifteen.

Now let's say that we only want odd indices.

To do this, we can use all three of the parameters.

So the first is the start parameter, starting at one.

The end, or the stop value. And now the step.

By default the step is one, so we go from values one to two to three.

I'm going to increase the step to two, getting values one, three, five, seven and

so on. And that gives us the odd indices to the

string S.