[Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?
Peter Otten
__peter__ at web.de
Wed Oct 28 12:27:46 EDT 2015
Flynn, Stephen (L & P - IT) wrote:
> Afternoon,
>
> 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 the list is small you can slice it:
assert items
for item in things[:-1]:
print(item, ",", sep="")
print(items[-1])
I have written a generator similar to
>>> def g(items):
... items = iter(items)
... try:
... prev = next(items)
... except StopIteration:
... return
... for item in items:
... yield False, prev
... prev = item
... yield True, prev
...
>>> for islast, item in g("abc"):
... print(item, "(done)" if islast else "(to be continued)", sep="")
...
a(to be continued)
b(to be continued)
c(done)
but only used it once ore twice.
> 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...
>
> e.g.
> CREATE TABLE wibble
> (
> Col1 CHAR(2),
> Col2 NUMBER(5,2),
> );
This particular problem can idiomatically be addressed with str.join():
>>> print(",\n".join(["foo", "bar", "baz"]))
foo,
bar,
baz
More information about the Tutor
mailing list