[Tutor] a little loop

Steven D'Aprano steve at pearwood.info
Wed May 29 04:34:52 CEST 2013


On 28/05/13 13:54, Tim Hanson wrote:
> Okay, so I made it to FOR loops in the Lutz book.  A couple of days ago I was
> helped here with the .join method for creating strings from lists or tuples of
> strings.  I got to wondering if I could just, for the sake of learning, do the
> same thing in a FOR loop, since that's today's chapter:
>
> x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
> for t in b:
> 	ham=ham+b[x]
> 	print(ham);x+=1

There's no need to manually count the index that you are looking at, and no need to manually look up the character using b[x]. That's what the for-loop is already doing. (Also, a good habit to get into is using *meaningful* variable names, not one-letter cryptic names.)


ham = ''
for char in ['s', 'p', 'a', 'm']:
     ham = ham + char
     print(ham)


But wait, there's more! There's no need to split the string "spam" up into characters yourself, since strings can be iterated over too:

ham = ''
for char in 'spam':
     ham = ham + char
     print(ham)


However, a word of warning: although you *can* assemble a new string character by character like that, you should not, because it risks being very slow. *Painfully* slow. If you want to hear the details, please ask, but it risks being slow for much the same reason as the infamous Shlemiel the Painter Algorithm:

http://www.joelonsoftware.com/articles/fog0000000319.html


So while it is okay to assemble strings using + if there are only a few pieces, you should avoid doing it whenever there is a chance of there being many pieces. The standard method for assembling a string from a collection of substrings is to do it in one go, using the join method, instead of piece by piece:

pieces = ['NOBODY', 'expects', 'the', 'Spanish', 'Inquisition!']
mystring = ' '.join(pieces)  # join with a single space between each piece
print(mystring)


The joiner can be any string you like, including the empty string '', it doesn't have to be a space.



-- 
Steven


More information about the Tutor mailing list