Iterating over multiple lists (a newbie question)

Tim Peters tim.one at home.com
Sun Jan 7 04:09:53 EST 2001


[Alex Martelli]
> ...
> The map builtin function, OTOH, does need to know the length of
> each sequence in advance (and the _longest_ one controls, with
> the others being 'extended' with as many 'None' as needed), so,
> no such techniques (tricks?-) are available in that case.

Actually, they are.  map is controlled by IndexError, same as everything
else.  It's a rather muddy historical tale as to why it insists that len(s)
be defined for each sequence argument s, but the largest of those is used
only as "a hint", to preallocate a result list.  If the last occurrence of
IndexError occurs before or after that length is reached, map shrinks or
grows the result list accordingly.

>>> class Liar:
	def __getitem__(self, i): # really has length 3
	    return "abc"[i]

>>> class LowLiar(Liar):
        def __len__(self): return 0

>>> class HighLiar(Liar):
        def __len__(self): return 100000

>>> x = LowLiar()
>>> len(x)
0
>>> map(None, x)
['a', 'b', 'c']
>>> y = HighLiar()
>>> len(y)
100000
>>> map(None, y)
['a', 'b', 'c']
>>>





More information about the Python-list mailing list