[Tutor] a little loop
Alan Gauld
alan.gauld at btinternet.com
Tue May 28 09:38:14 CEST 2013
On 28/05/13 04:54, Tim Hanson wrote:
> 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
>
> Alright, it works, eventually. Can someone help me find a little more elegant
> way of doing this? I'm sure there are several.
Python 'for' loops iterate over the target sequence so you usually don't
need indexes. (And if you do you should use enumerate()). If it helps
read the word 'for' as 'foreach'. So rewriting your for loop in
a Pythonic style yields:
for letter in b:
ham += letter
print(ham)
or if you must for some reason use indexing try
for index, letter in enumerate(b):
ham += b[index]
print(ham)
Note however that string addition is very inefficient compared to
join(), so in the real world you are much better off using join.
There are other ways of doing this but join() is best so
there is little point in reciting them.
Notice also that I used 'letter' as the loop variable. Meaningful names
make code much easier to understand. The extra effort of typing is
easily offset by the time saved reading the code later.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list