Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a slice?

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?

like image 810
JoePythonKing Avatar asked Mar 01 '19 09:03

JoePythonKing


People also ask

How do you iterate a slice in Golang?

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.

How do I iterate a list in Golang?

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.


1 Answers

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]
like image 144
Zero Piraeus Avatar answered Sep 29 '22 03:09

Zero Piraeus