Initializing a list with copies

Alex Martelli aleax at aleax.it
Tue Apr 30 10:18:03 EDT 2002


Ralf Juengling wrote:
        ...
> BTW: It is not easy to add __iter__ to list's meta-type, is it?

list's "metatype" (metaclass) is the built-in type named 'type'.
like for all other built-in types and new-style classes.  Adding
__iter__ to type would thus make almost 'everything' iterable.

And giving list a different metaclass than all the other types
would no doubt be weird.

Further, it would be utterly weird if 'take' was introduced,
operated correctly on iterables (including iterators), but
returned a list rather than an iterator!  It would freak me
out... we finally have a 'lazy' paradigm, and we'd just
throw it away like this?!  take and drop should both accept
and return iterators.  You can make any (bounded) iterator
into a list by calling list on it, just like you can make
a bounded iterator from any sequence by calling iter.

If we had 'take', you could already use it for such purposes:

>>> from __future__ import generators
>>> def take(n, iterable):
...     for item in iterable:
...         if n<=0: raise StopIteration
...         n -= 1
...         yield item
...
>>> List2D = list(take(5, iter(list, '')))
>>> List2D
[[], [], [], [], []]
>>>

Remember the two-arguments form of iter lets you make ANY
callable-without-arguments into an iterator -- no need to
muck around with 'type' or anything like that.

I don't see what's more elegant in this way to build List2D
than the obvious list-comprehension:

List2D = [ [] for i in xrange(5) ]

but that's another issue.


Alex




More information about the Python-list mailing list