[swift-evolution] Proposal: Python's indexing and slicing

Joe Groff jgroff at apple.com
Fri Dec 18 15:46:46 CST 2015


> On Dec 18, 2015, at 4:42 AM, Amir Michail via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Examples:
> 
> >>> l=[1,2,3,4,5]
> >>> l[-1]
> 5
> >>> l[-2]
> 4
> >>> l[2:4]
> [3, 4]
> >>> l[2:]
> [3, 4, 5]
> >>> l[-2:]
> [4, 5]
> >>> l[:3]
> [1, 2, 3]
> >>> l[::2]
> [1, 3, 5]
> >>> l[::]
> [1, 2, 3, 4, 5]

Accepting negative indices is problematic for two reasons: it imposes runtime overhead in the index operation to check the sign of the index; also, it masks fencepost errors, since if you do foo[m-n] and n is accidentally greater than m, you'll quietly load the wrong element instead of trapping. I'd prefer something like D's `$-n` syntax for explicitly annotating end-relative indexes.

-Joe

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/24d11866/attachment.html>


More information about the swift-evolution mailing list