[Tutor] double result ... [home on the range()]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Nov 16 17:27:26 EST 2003



On Sun, 16 Nov 2003, Tadey wrote:

> >>> a=7
> >>> b=9
> >>> c=8
> >>> for i in range(a,b,c):
> >>>    print i
> ...
> ...
> 7
>
>
> ... gives value a, becuse it is the first value in the row, and because
> a, b, c are no "logical sequence" for computer (it doesn't support
> alphabet) !!


Hi Tadey,

Ah!  range() is a sequence builder, but it's not the only one --- you can
directly build sequences by using lists:

###
>>> [3, 7, 19, 42]
[3, 7, 19, 42]
>>>
>>>
>>> mylist = [7, 9, 8]
>>> mylist
[7, 9, 8]
>>> mylist[0]
7
>>> mylist[1]
9
###



But range() is meant to make it easy to generate lists of ascending
numbers:

###
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10, 20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> range(10, 20, 3)
[10, 13, 16, 19]
###

So those numbers that we feed it are meant to be used as "endpoints" of a
number range.

range() can take in either one, two, or three arguments, and it behaves
slightly differently in each case.  The third case is asking Python: "Give
me the range of numbers between 10 and 20, by skipping foward three
numbers at a time."

Once we understand range(), then it should be easier to see why:

    range(7, 9, 8)

is only giving us

    [7]

--- There's only one number between 7 and 9, if we skip 8 numbers forward
at a time.


But if we try getting the numbers from 10 to 0, by stepping forward 1
at a time, we're sunk:

###
>>> range(10, 0, 1)
[]
###


But, by the way, we can go "backwards", just as long as the step is
negative:

###
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
###



Does this make sense so far?  Please feel free to ask more questions about
this.

Hope this helps!




More information about the Tutor mailing list