transforming a list into a string

Peter Otten __peter__ at
Sun Aug 1 20:14:15 CEST 2004

Roy Smith wrote:

> I'm also not particularly happy about the choice of "it" as a variable
> name.  The "izip (it, it)" construct makes me think of Dr. Evil :-)

Using "it" is just my convention (contradictio in adiecto :-) for iterators
used in a pure algorithm rather than with a meaning determined by a
concrete use case. It's similar to the traditional i in counting loops,
having grown an additional "t" to disambiguate it. If you have a better
name for the purpose, don't hesitate to tell me...

> It's not the izip bit that bothers me in the original, it's the deeply
> nested construct of
> ",".join(["{%s,%s}" % i for i in izip(it, it)])
> There's too much going on in that one line to get your head around
> easily.  I suppose people who are really into functional programming
> might find it understandable, but I find it rather obtuse.

I don't think three levels can be called "deep nesting". In particular the
"somestr".join() construct is so ubiquitous that your brain will "optimize"
it away after reading a small amount of Python code. But I see my oneliner
meets serious opposition. Well, sometimes a few self-explanatory names and
a helper function can do wonders:

import itertools

def pairs(seq):
    it = iter(seq)
    return itertools.izip(it, it)

coords = ['1','2','7','8','12','13']
points = []
for xy in pairs(coords):
    points.append("{%s, %s}" % xy)

print ", ".join(points)

That should be clear even to someone who has never heard of generators. Note
that pairs() is only called once and therefore does not affect the speed of
execution. Personally, I'd still go with the list comprehension instead of
the above for-loop.

By the way - expanding on Michele Simionato's chop(),
I've written a generalized version of pairs():

_missing = object()

def ntuples(seq, N=2, filler=_missing):
    """ Yield a sequence in portions of N-tuples.

        >>> list(ntuples("abcdefg", 3))
        [('a', 'b', 'c'), ('d', 'e', 'f')]

        >>> list(ntuples("abc", filler="x"))
        [('a', 'b'), ('c', 'x')]
    if filler is _missing:
        it = iter(seq)
        it = itertools.chain(iter(seq), itertools.repeat(filler, N-1))
    iters = (it,) * N
    return itertools.izip(*iters)

Enjoy :-)


More information about the Python-list mailing list