It is better to be explicit and just allow stop to be None.
If \var{start} is non-zero, then elements from the iterable are skipped
until start is reached. Afterward, elements are returned consecutively
unless \var{step} is set higher than one which results in items being
- skipped. If \var{stop} is not specified or is \code{None}, then iteration
- continues indefinitely; otherwise, it stops at the specified position.
- Unlike regular slicing,
+ skipped. If \var{stop} is \code{None}, then iteration continues until
+ the iterator is exhausted, if at all; otherwise, it stops at the specified
+ position. Unlike regular slicing,
\function{islice()} does not support negative values for \var{start},
\var{stop}, or \var{step}. Can be used to extract related fields
from data where the internal structure has been flattened (for
\begin{verbatim}
def islice(iterable, *args):
- if args:
- s = slice(*args)
- next = s.start or 0
- stop = s.stop
- step = s.step or 1
- else:
- next, stop, step = 0, None, 1
+ s = slice(*args)
+ next = s.start or 0
+ stop = s.stop
+ step = s.step or 1
for cnt, element in enumerate(iterable):
if cnt < next:
continue
self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
# Test stop=None
- self.assertEqual(list(islice(xrange(10))), range(10))
self.assertEqual(list(islice(xrange(10), None)), range(10))
self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
# Test invalid arguments
+ self.assertRaises(TypeError, islice, xrange(10))
self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
isliceobject *lz;
numargs = PyTuple_Size(args);
- if (!PyArg_ParseTuple(args, "O|OOl:islice", &seq, &a1, &a2, &step))
+ if (!PyArg_ParseTuple(args, "OO|Ol:islice", &seq, &a1, &a2, &step))
return NULL;
if (numargs == 2) {
return NULL;
}
}
- } else if (numargs == 3 || numargs == 4) {
+ } else {
start = PyInt_AsLong(a1);
if (start == -1 && PyErr_Occurred()) {
PyErr_Clear();