Newbie: last item of a loop
Alex Martelli
aleax at aleax.it
Fri May 2 12:04:46 EDT 2003
Sven Brandt wrote:
> Sorry, I mixed up some of the variable names. Here is the correct code:
>
> my_names=['Peter', 'Paul','Mary']
> my_name_string=''
>
> for i in my_names:
> # if more than one name
> if len(my_names) > 1:
> # if not last or second-last name, append komma
> if i.index < len(my_names) - 1:
> my_name_string = my_name_string + ', '
> # if second-last append 'and'
> if i.index == len(my_names) - 1:
> my_name_string = my_name_string + ' and '
This looks unduly complicated to me. It appears that what you want
to do is:
join with the joiner-string ' and ' a sequence of up to two pieces,
the first piece, if any, joins with the joiner-string ', ' all items
up to the last one of my_names, excluded,
the other piece is the last item of my_names
with the understanding that "joining" a sequence of just one item
returns that item, "joining" an empty sequence gives the empty string.
The Python way to ask a joiner-string to join a sequence of strings is:
joiner.join(sequence)
The Python way to say "all items up to the last one excluded" is seq[:-1];
to say "the last item", seq[-1].
So, to break things down into simple, clear steps, we might say:
first_part = ', '.join(my_names[:-1])
if first_part:
my_name_string = ' and '.join([first_part, my_names[-1]])
else:
my_name_string = my_names[-1]
Of course, many small details could be changed here; for example,
knowing that the parts joined by ' and ' are exactly two, one might
prefer another way of expressing things, such as:
first_part = ', '.join(my_names[:-1])
if first_part:
first_part += ' and '
my_name_string = first_part + my_names[-1]
for conciseness and simplicity.
Alex
More information about the Python-list
mailing list