[Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?
Cameron Simpson
cs at zip.com.au
Wed Oct 28 18:22:50 EDT 2015
On 28Oct2015 14:48, Flynn, Stephen (L & P - IT) <Steve.Flynn at capita.co.uk> wrote:
> Python 3.
>
> I'm iterating through a list and I'd like to know when I'm at
>the end of the said list, so I can do something different. For example
>
>list_of_things = ['some', 'special', 'things']
>for each_entry in list_of_things:
> print(each_entry)
> if each_entry == list_of_things[-1]: # do something special to
>last entry
> ...etc
>
>Is this the idiomatic way to detect you're at the last entry in a list
>as you iterate through it?
If it really is a list then enumerate is your friend.
list_of_things = ['some', 'special', 'things']
last_index = len(list_of_things) - 1
for index, each_entry in enumerate(list_of_things):
print(each_entry)
if index == last_index:
... special stuff for the last index ...
>For context, I'm working my way through a (csv) file which describes
>some database tables. I'm building the Oracle DDL to create that table
>as I go. When I find myself building the last column, I want to finish
>the definition with a ");" rather than the usual "," which occurs at the
>end of all other column definitions...
This is a bit different, in that you are probably not using a list: you don't
know how long the sequence is.
I build things like that this way:
fp.write('CREATE TABLE wibble\n(')
sep = '\n '
for item in items:
fp.write(sep)
fp.write(... column definition for item ...)
sep = ',\n '
fp.write('\n);\n')
i.e. instead of printing the separator _after_ each item, print it _before_.
That way you can special case the first occasion and use a comma for each
successive occasion.
Cheers,
Cameron Simpson <cs at zip.com.au>
Why is it whatever we don't understand is called a 'thing'? - "Bones" McCoy
More information about the Tutor
mailing list