Skip to content Skip to sidebar Skip to footer

Last Element In A Python Iterator

I want to iterate through the lines of a file, and print some output for each of them. All lines printed should have a ,\n at the end, except for the last line. My first approach w

Solution 1:

Print first line on its own, and then other lines prepended by ",\n".

firstline = next(thefile)
print get_some_output(firstline)
for line in thefile:
    print ",\n" + get_some_output(line)

Solution 2:

Here is a wrapper class for an iterator that does give you a hasNext property:

class IteratorEx(object):
    def __init__(self, it):
        self.it = iter(it)
        self.sentinel = object()
        self.nextItem = next(self.it, self.sentinel)
        self.hasNext = self.nextItem is not self.sentinel

    def next(self):
        ret, self.nextItem = self.nextItem, next(self.it, self.sentinel)
        self.hasNext = self.nextItem is not self.sentinel
        return ret

    def __iter__(self):
        while self.hasNext:
            yield self.next()

Demo:

iterex = IteratorEx(xrange(10)) 
for i in iterex:
    print i, iterex.hasNext

Prints:

0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 True
8 True
9 False

Solution 3:

You presumably want to strip off the existing newlines first. Then you can iterate through the stripped lines, get your output, and join the results together using ", \n", like so:

f = open('YOUR_FILE', 'r')
print ",\n".join([get_some_output(line.rstrip("\n")) for line in f])

Solution 4:

Answers relevant to your question appear in several of the posts listed below. Although some of these questions differ significantly in intent from the present question, most of them have such informative answers I've listed them here anyway. Note, Pavel's answer is a cleaner solution to the current problem than will be found in the following, but a few of the older answers apply more generally.

Python: Looping through all but the last item of a list,
Have csv.reader tell when it is on the last line,
Getting the first and last item in a python for loop,
What is the pythonic way to detect the last element in a python 'for' loop?
Python How to I check if last element has been reached in iterator tool chain,
Cleanest way to get last item from python iterator,
How to treat the last element in list differently in python?,
Python: how do i know when i am on the last for cycle,
Ignore last \n when using readlines with python,
Python Last Iteration in For Loop,
Python 3.x: test if generator has elements remaining

One of the above was listed in the right-sidebar's “Related” list for the present question, but the others were not. Several of the questions in the “Related” sidebar are worth looking at and could have been included in the list above.


Post a Comment for "Last Element In A Python Iterator"