patternpythonMinor
Iteritems on a slice of a Python list
Viewed 0 times
listpythoniteritemsslice
Problem
iteritems on a dict can useful.Occasionally
iteritems is useful for a slice of a list and this effect can be (crudely) implemented as follows:class List(list):
def iteritems(self, slice=None):
if slice is None: return enumerate(self)
else: return itertools.izip(range(*slice.indices(len(self))), self[slice])
if __name__ == "__main__":
l=List("hAnGtEn")
print l
print list(l.iteritems())
print list(l.iteritems(slice(1,None,2)))Output:
['h', 'A', 'n', 'G', 't', 'E', 'n']
[(0, 'h'), (1, 'A'), (2, 'n'), (3, 'G'), (4, 't'), (5, 'E'), (6, 'n')]
[(1, 'A'), (3, 'G'), (5, 'E')]Is there a more "pythonic" list slicing syntax that should be used?
This:
range(slice.start,slice.stop,slice.step)does not handle certain special cases very well: e.g. where
stop=-1, start=None or step=None. How can the example range/slice implementation be also improved?edit:
range(slice.start,slice.stop,slice.step)is better handled with:
range(*slice.indices(len(self)))Solution
Instead of
you could use this expression that handles the special cases too
(This works with
range(slice.start,slice.stop,slice.step)you could use this expression that handles the special cases too
range(len(self))[slice](This works with
range on both Python 2 and 3, but not with Python 2 xrange even though it is mostly equivalent to Python 3 range)Code Snippets
range(slice.start,slice.stop,slice.step)range(len(self))[slice]Context
StackExchange Code Review Q#70959, answer score: 3
Revisions (0)
No revisions yet.