# HG changeset patch # User Paul Boddie # Date 1480457598 -3600 # Node ID 639a285a92feb5a62667ca8eeca6010a12cf0164 # Parent 03dad612d9e7c50fde962774f5289cf80fa9f755 Added the index method to sequences. Raise TypeError instances. diff -r 03dad612d9e7 -r 639a285a92fe lib/__builtins__/sequence.py --- a/lib/__builtins__/sequence.py Tue Nov 29 23:12:15 2016 +0100 +++ b/lib/__builtins__/sequence.py Tue Nov 29 23:13:18 2016 +0100 @@ -62,6 +62,19 @@ return False + def index(self, value): + + "Return the index of 'value' or raise ValueError." + + i = 0 + l = len(self) + while i < l: + if self[i] == value: + return i + i += 1 + + raise ValueError(value) + def __getitem__(self, index): "Return the item or slice specified by 'index'." @@ -81,7 +94,7 @@ # No other kinds of objects are supported as indexes. else: - raise TypeError + raise TypeError() def __setitem__(self, index, value): @@ -102,7 +115,7 @@ # No other kinds of objects are supported as indexes. else: - raise TypeError + raise TypeError() def __getslice__(self, start, end=None): diff -r 03dad612d9e7 -r 639a285a92fe tests/list.py --- a/tests/list.py Tue Nov 29 23:12:15 2016 +0100 +++ b/tests/list.py Tue Nov 29 23:13:18 2016 +0100 @@ -33,3 +33,11 @@ print 4 not in l # True print "four" not in l # False print "one" not in l # True + +print l.index(1) # 0 +print l.index("four") # 3 + +try: + print l.index(4) # should raise an exception +except ValueError, exc: + print "l.index(4): failed to find argument", exc.value