Why are slice and range upper-bound exclusive?

Disclaimer: I am not asking if the upper-bound stopargument of slice()and range() is exclusive or how to use these functions. Calls to the rangeand slicefunctions, as well as the slice notation [start:stop] all refer to sets of integers. range([start], stop[, step]) slice([start], stop[, step]) In all these, the stop integer is excluded. I am wondering … Read more

What is the idiomatic way to slice an array relative to both of its ends?

Powershell’s array notation has rather bizarre, albeit documented, behavior for slicing the end of arrays. This section from the official documentation sums up the bizarreness rather well: Negative numbers count from the end of the array. For example, “-1” refers to the last element of the array. To display the last three elements of the … Read more

How to return all except last 2 characters of a string?

id = ’01d0′; document.write(‘<br/>’+id.substr(0,-2)); How can I take a string like ’01d0and get the01` (all except the last two chars)? In PHP I would use substr(0,-2) but this doesn’t seem to work in JavaScript. How can I make this work? Answer You are looking for slice() (also see MDC) id.slice(0, -2) AttributionSource : Link , … Read more

Use slice notation with collections.deque

How would you extract items 3..6 efficiently, elegantly and pythonically from the following deque without altering it: from collections import deque q = deque(”,maxlen=10) for i in range(10,20): q.append(i) the slice notation doesn’t seem to work with deque… Answer import itertools output = list(itertools.islice(q, 3, 7)) For example: >>> import collections, itertools >>> q = … Read more