Faster way to do this...

Roy Smith roy at panix.com
Tue Mar 1 16:43:10 CET 2005


Harlin Seritt <harlinseritt at yahoo.com> wrote:
>I've got the following code:
>
>nums = range(0)
>for a in range(100):
>   nums.append(a)
>
>Is there a better way to have num initialized to a list of 100
>consecutive int values?

Step one would be to change the first line to

nums = []

which is simpler and results in the same thing.  Or, you could write
the whole thing as a one-liner using a list comprehension

nums = [a for a in range(100)]

and then you can take it one step further and just write

nums = range(100)

which I think is about as simple as you can get.



More information about the Python-list mailing list