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?
Code explanation Line 4: Program execution in Golang starts from the main() function. Line 7: We declare and initialize the slice of numbers, n . Line 10: We declare and initialize the variable sum with the 0 value. Line 13: We traverse through the slice using the for-range loop.
Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.
A slice
isn't an iterable. It doesn't contain elements, but instead specifies which elements in some other iterable are to be returned if the slice is applied to that iterable.
Since it's not an iterable, you can't iterate over it. As you have discovered, however, you can obtain the indices for which it will return elements from an iterable to which it is applied, using range()
- and you can iterate over that:
s = slice(1, 10, 2)
indices = range(s.start, s.stop, s.step)
it = iter(indices)
>>> list(it)
[1, 3, 5, 7, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With