transforming a list into a string

Terry Reedy tjreedy at udel.edu
Sun Aug 1 20:04:34 EDT 2004


"Tim Peters" <tim.peters at gmail.com> wrote in message
news:1f7befae040731171654c11ec6 at mail.gmail.com...
> Absolutely.  Note that Peter Otten previously posted a lovely O(N)
> solution in this thread, although it may be too clever for some
> tastes:
>
> >>> from itertools import izip
> >>> items = ['1','2','7','8','12','13']
> >>> it = iter(items)
> >>> ",".join(["{%s,%s}" % i for i in izip(it, it)])
> '{1,2},{7,8},{12,13}'

While this usage of izip(it,it) is clever (and zip(it,it) behaves the
same), it *breaks* the documented behavior of zip and hence of izip, and
depends on seemingly inessential implementation details of zip/izip (which
is only documented for izip).

The Lib Manual 2.1 zip entry calls the args 'sequences' whereas it should
say 'iterables'.  It goes on "This function returns a list of tuples, where
the i-th tuple contains the i-th element from each of the argument
sequences. ... The returned list is truncated in length to the length of
the shortest argument sequence."  In fact, even back in 2.2:
>>> it = iter([1,2,3,4])
>>> zip(it,it)
[(1, 2), (3, 4)]

I believe the definition of zip would allow iterator inputs to be handled
by list()ing them (for instance, left to right).  A reason to do this might
be to fix the otherwise unknown lengths so that the min could be determined
so that the output list could be preallocated.  If this were done, however,
zip(it,it) would output [] instead.

If zip were to build output tuples from the end, which the definition would
also seem to allow, then zip(it,it) above would be [(2,1), (4,3)] instead.
Zip's behavior seems to me undefined for this corner case.

So the doc needs to be updated to specify the args as iterables, not
restricted to sequences, and qualify the 'usual' behavior as depending on
having distinct iterator inputs.

The 5.14.1 Itertool functions izip entry says simply "Like zip() except
that it returns an iterator instead of a list."  It also give 'equivalent'
Python code which happens to pin down the behavior for this corner case.  I
wonder if this code should really be taken as determinative documentation
rather than as illustrative of possible implementation.  (I may ask RH if
need be.)  If the former, then the zip doc could reference the izip
equivalent code as specifying its behavior.

Terry J. Reedy






More information about the Python-list mailing list