islice ==> [::]

Raymond Hettinger python at rcn.com
Fri Mar 7 14:14:38 EST 2008


[bearophileH]
> I find itertools.islice() useful, so for Python 3.x I may like to see
> it removed from the itertools module, and the normal slicing syntax
> [::] extended to work with generators/iterators too.

This is a can of worms.  First, remember iterations is a protocol, not
a type.  So, this would have to be added to every possible iterator
class (dict.iteritems() and enumerate() for example).  Second, he who
wants slicing, at some time will want getitem, but Guido ruled this
out long ago saying that it is a mistake to conflate sequences and
general iterables.  Third, the analogy breaks down quickly (i.e.
chain(it[:2], it[2:]) does not give the same result as iter(it) unless
working on a re-iterable sequence).  Fourth, this suggests other
related hyper-generalizations which also break down in practice (i.e.
using the plus operator for chain() breaks down when you write it+it
and find that the second one is fully consumed by the time chain()
gets to it).

Besides, if you know what you're doing it is simple to write a trivial
wrapper class that temporarily supports the slicing notation:

class W:
	def __init__(self, it):
		self.it = iter(it)
	def __getitem__(self, n):
		if isinstance(n, slice):
			return islice(self.it, n.start, n.stop, n.step)
		return islice(self.it, n, n+1)

>>> s = 'abcdefg'
>>> list(W(s)[2:])
['c', 'd', 'e', 'f', 'g']
>>> list(W(s)[:2])
['a', 'b']
>>> list(W(s)[::2])
['a', 'c', 'e', 'g']
>>> list(W(s)[2])
['c']



Raymond



More information about the Python-list mailing list