[Tutor] Iterating over multiple lists- options

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Feb 7 10:32:09 CET 2005



On Mon, 7 Feb 2005, Tony Cappellini wrote:

> There are 4 lists total, each of which *may* have a different length
> from the other lists. Each list has been stored in a master dictionary.
>
> North=[Bill, Bob, Sue, Mary]
> South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich']
> etc
>
> I want to iterate over all the lists a the same time, so I can populate an
> html table.

[some text cut]

> Looking through my books on Python I've found examples for zip() and map()
> both of which have serious shortcomings


Hi Tony,

Out of curiosity, if it's not possible to run zip() directly on the lists
that you have, can you bend the lists so that zip() will fit?


Here's a quick function that should force a certain length on an iterator:

###
def ipad(iterable, length, sentinel=None):
    """Returns a new iterator whose elements are taken from iterator.  If
    there are fewer elements than 'length', we pad the rest with
    sentinels.

    Assumptions: len(iterator) <= length.  The result from ipad never
    truncates the elements out of i, so the iterator always goes through
    all the elements in iterable.
    """
    i = 0
    for thing in iterable:
        yield thing
        i = i + 1
    while i < length:
        yield sentinel
        i = i + 1
###


For example:

###
>>> names = ['knuth', 'mcconnell', 'bentley', 'witten']
>>> for n in ipad(names, 7):
...     print n
...
knuth
mcconnell
bentley
witten
None
None
None
>>>
>>>
>>> for n in ipad(names, 2):
...     print n
...
knuth
mcconnell
bentley
witten
###


So we could use something like ipad() to bring all the lists to the same
length, and that should make it suitable for zip().


Hope this helps!



More information about the Tutor mailing list