Dumb python questions

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 15 07:06:40 EDT 2001


Paul Rubin <phr-n2001 at nightsong.com> wrote in
news:7xofphd4ql.fsf at ruckus.brouhaha.com: 

> xrange apparently doesn't malloc the values until they're used, but
> they eventually get malloc'd.  I think functional programming has run
> slightly amuck here.  What's wanted is something equivalent to
> 
>    sum = 0
>    i = 1
>    while i <= 100 :
>       sum = sum + i
>       i = i + 1
Well, you can write that if that is what you want. I think you are 
confusing Python's for loop with the for loop in languages like C. In 
Python, 'for' is for iterating over the elements of a sequence. This is 
actually a very common operation, almost certainly more so than adding up 
the numbers in a range.
Also, you say that xrange still eventually creates all of the numbers in 
the range, but so does your while loop. Any loop eventually has to create 
or access every index value that it uses. For a list of 100 numbers, it is 
generally much faster for Python to create the list than it is for it to 
create each of the numbers by adding 1 to the preceding value.

> Python is really pleasant to code in and mostly well designed.  I just
> keep hitting what seem like little lapses of common sense.
My opinion is that the for loop in Python is one of the things that makes 
it great.

> Here's another one: the print statement puts a gratuituous space after
> each thing you print.  So
> 
>    for i in ['a','b','c']:
>      print i,
> 
> prints "a b c " instead of "abc".
Actually it prints "a b c", there isn't a space after the last value. The 
space is inserted in front of each value, except at the start of a line.

Most of the time this is what you (or at least I) want. If you want "abc" 
then try one of the following:

import sys
for i in ['a', 'b', 'c']:
   sys.stdout.write(i)

Or build the line up before printing it:
line = ""
for i in ['a', 'b', 'c']:
   line += i
print line

Or:
>>> def nospace(value):
...    "suppress space before this value"
...    sys.stdout.softspace = 0
...    return value
...
>>> for i in ['a', 'b', 'c']:
...    print nospace(i),
...
abc
>>>


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list