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.

Â