Newbie: last item of a loop

Sven Brandt sven_NOSPAM at manastar.de
Fri May 2 08:38:09 EDT 2003


Hi Anton,

to be more precise:

I have a list of names which I want as a joined string, seperated by 
kommas except for the last item which is seperated by 'and'. ['Peter', 
'Paul','Mary'] -> 'Peter, Paul and Mary'

here is what I tried (I know that the 'i.index' does not give me the 
index-number of the sequence item, but I don't know better. Sorry. But I 
hope you get the point ...) :

my_names=['Peter', 'Paul','Mary']
my_name_string=''

for i in my_names:
   # if more than one name
   if len(driver_names) > 1:
     # if not last or second-last name append komma
     if i.index  < len(driver_names) - 1:
       driver_names_string = driver_names_string + ', '
     # if second-last append 'and'
     if i.index  == len(driver_names) - 1:
       driver_names_string = driver_names_string + ' und '

> l = ['a', 'b', 'c', 'd']
> 
> # process l[0]
> for e in l[1:-1]:
>     # process inner elements
> # process l[-1]

This would do but I prefere to have it in one loop for better readability.

Thanx for your help!
Regards Sven





More information about the Python-list mailing list