A slice
in python is not iterable. This code:
s = slice(1, 10, 2)
iter(s)
results in this error:
TypeError: 'slice' object is not iterable
This is the code I've come up with to show the slice by creating a list iterable:
list(range(s.start, s.stop, s.step))
This uses the start
, stop
and step
attributes of the slice object. I plug those into a range (an immutable sequence type) and create a list:
[1, 3, 5, 7, 9]
Is there something missing? Can I iterate over a slice any better?