[].keys() and [].items() (Was: Why I think range is a wart)

James_Althoff at i2.com James_Althoff at i2.com
Thu Mar 14 16:04:14 EST 2002


Here's a q&d sample implementation in case anyone wants to test out the
idea before deciding on its merits.

Jim

========================


from __future__ import generators

class List(list):

    def keys(self):
        return range(len(self))

    def iterkeys(self):
        return iter(xrange(len(self)))

    def values(self): # polymorphic with dicts
        return self

    def itervalues(self):  # polymorphic with dicts
        return iter(self)

    def items(self):
        return zip(self.keys(),self)

    def iteritems(self):
        keys = self.iterkeys()
        values = self.itervalues()
        while 1:
            try:
                yield keys.next(),values.next()
            except StopIteration:
                raise

def test(l=None):
    if l is None:
        l = List(['a','b','c','d'])
    print
    for index in l.keys():
        print index,
    print
    for index in l.iterkeys():
        print index,
    print
    for value in l.values():  # polymorphic with dicts
        print value,
    print
    for value in l.itervalues():  # polymorphic with dicts
        print value,
    print
    for index,value in l.items():
        print (index,value),
    print
    for index,value in l.iteritems():
        print (index,value),
    print; print

>>>
>>> l = List(['a','b','c'])
>>> test(l)

0 1 2
0 1 2
a b c
a b c
(0, 'a') (1, 'b') (2, 'c')
(0, 'a') (1, 'b') (2, 'c')

>>>







More information about the Python-list mailing list