[Tutor] Odds and even exercise

Steven D'Aprano steve at pearwood.info
Sun Mar 28 00:23:44 CET 2010


On Sun, 28 Mar 2010 09:33:23 am yd wrote:

> I find it easy to do all this stuff with list comprehensions, but
> i am a beginner so this might not be the most efficient way to do it
>
> numbers=[]
> for x in range(1,101):
>     numbers.append(x)

That certainly isn't efficient! In Python 2.x, this is what it does:

(1) Create an empty list and call it "numbers".
(2) Create a list [1, 2, ... 100]
(3) Set up a for-loop.
(4) Read the first number from the list (1) and call it x.
(5) Add x to the end of numbers.
(6) Read the second number from the list (2) and call it x.
(7) Add x to the end of numbers.
(8) Read the third number from the list and call it x.
(9) Add x to the end of numbers.
...
(202) Read the 100th number from the list and call it x.
(203) Add x to the end of numbers.
(204) Finish up the for-loop.

Better to just say:

(1) Create a list [1, 2, ... 100] and call it "numbers".

numbers = range(1, 101)

In Python 3.x, it is exactly the same except for step 2, which creates a 
lazy range-object which only stores one item at a time. So the solution 
in Python 3.x is to convert it into a list:

numbers = list(range(1, 101))


> > #A way to display all odd numbers
> > odd = numbers[::2]
>
>   instead i do this:
>   odd=[]
>   for y in range(1,101,2):
>     odd.append(y)


This does just as much unnecessary work as above.



-- 
Steven D'Aprano


More information about the Tutor mailing list