[Tutor] trivial simple program..can it be made more concise?

Peter Otten __peter__ at web.de
Sat Feb 14 08:38:41 CET 2015


steve10brink at comcast.net wrote:

> I was playing with Python tonight and created a simple program that
> outputs numbers counting up then counting down all on the same terminal
> line. The code is as follows:
> 
> 
> 
> #------------------------------------------------------------
> a = 320000 #number to count up to
> 
> 
> for i in range (a):
> print i, '\r',
> 
> for i in range ((a-1),0,-1):
> print i, '\r',
> 
> #------------------------------------------------------------
> 
> 
> 
> 
> It works as desired. However, I was trying to figure out a way to make it
> more concise but
> 
> cannot see a way since the 'range' parameters must be integers (no
> functions allowed?).

> Anyone see a way to simplify it?

r = range(320000)
for i in r + r[::-1]:
    print i, "\r",

However, this has the disadvantage of building a list with 620000 items. To 
avoid that you can write

from itertools import chain

r = xrange(320000)
for i in chain(r, reversed(r)):
    print i, "\r",

but you probably don't see that as a simplification.



More information about the Tutor mailing list