Generate lines from points in Python
When it comes to iteration in Python, there is often an itertools recipe or function that come close to the needs.

Here, I’m thinking about pairwise which is defined as:

def pairwise(iterable):
    "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)


If you’re interested in cycling back to the beginnig, you should consider itertools.cycle too:

def get_line_coordinates(iterable, close=False):
    """s -&gt; (s0,s1), (s1,s2), (s2, s3), ...
    ends with (sN, s0) if close is True else (sN-1, sN)
    """
    a, b = itertools.tee(iterable)
    if close:
        b = itertools.cycle(b)
    next(b, None)
    return itertools.izip(a, b)


Lastly, itertools.izip_longest will let you fill that last value by consumming less memory than cycle:

def get_line_coordinates(iterable, close=False):
    """s -&gt; (s0,s1), (s1,s2), (s2, s3), ...
    ends with (sN, s0) if close is True else (sN-1, sN)
    """
    a, b = itertools.tee(iterable)
    beginning = next(b, None)
    if close:
        return itertools.izip_longest(a, b, fillvalue=beginning)
    return itertools.izip(a, b)