Reputation: 5761
As we all know, we can easily extract data from arrays using slicing:
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
I often write a code when I need to use slicing as follows:
>>> L[ind:ind+x]
What I am curious now is: why there is no single operator to achieve that? For example in Verilog we could use slicing like:
>>> L[ind+:x]
Is there any other way to easily achieve that functionality?
Upvotes: 1
Views: 99
Reputation: 29099
There is no such syntax. The only thing to programmatically manipulate slicing is slice
objects.
i = slice(ind, ind+x)
print(x[i])
Upvotes: 1
Reputation: 164773
why there is no single operator to achieve that?
The syntax for list slicing hasn't changed since early versions of Python. The reason may be due to the judgement of an individual or influences from other languages. It is what it is. We must learn to live with it.
Is there any other way to easily achieve that functionality?
Well, sure. Note []
is syntactic sugar for __getitem__
and ind:ind+x
can be represented as a slice
object. Perhaps you prefer the second variation?
L = list(range(10))
L[3:7] # [3, 4, 5, 6]
m, k = 3, 4
L.__getitem__(slice(m, m+k)) # [3, 4, 5, 6]
Upvotes: 2
Reputation: 249444
No, Python does not have such a syntax. That's OK though--Python is not a language that prizes having ten ways to do everything.
Upvotes: 1