Game Development Reference
In-Depth Information
The
range()
and
list()
Functions
The
range()
function is easy to understand. You can call it with either one or two
integer arguments. When called with one argument,
range()
will return a range object of
integers from 0 up to (but not including) the argument. This range object can be converted
to the more familiar list data type with the
list()
function. Try typing
list(range
(10))
into the shell:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
The
list()
function is very similar to the
str()
or
int()
functions. It just converts
the object it is passed into a list. It's very easy to generate huge lists with the
range()
function. Try typing in
list(range(10000))
into the shell:
>>> list(range(10000))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15,...
...The text here has been skipped for
brevity...
...9989, 9990, 9991, 9992, 9993, 9994, 9995, 9996,
9997, 9998, 9999]
>>>
The list is so huge, that it won't even all fit onto the screen. But we can save the list into
the variable just like any other list by entering this:
>>> spam = list(range(10000))
>>>
If you pass two arguments to
range()
, the list of integers it returns is from the first
argument up to (but not including) the second argument. Try typing
list(range(10,
20))
into the shell:
>>> list(range(10, 20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
The
range()
is a very useful function, because we often use it in
for
loops (which are