Sida Zhou
Sida Zhou

Reputation: 3705

python array inclusive slice index

I wish to write a for loop that prints the tail of an array, including the whole array (denoted by i==0) Is this task possible without a branching logic, ie a if i==0 statement inside the loop?

This would be possible if there is a syntax for slicing with inclusive end index.

arr=[0,1,2,3,4,5]
for i in range(0,3):
    print arr[:-i]

output:

[]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]

wanted output:

[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]

Upvotes: 2

Views: 3506

Answers (4)

hpaulj
hpaulj

Reputation: 231385

The awkwardness arises from trying to take advantage of the :-n syntax. Since there's no difference between :0 and :-0, we can't use this syntax to distinguish 0 from the start from 0 from the end.

In this case it is clearer to use the :i indexing, and adjust the range accordingly:

In [307]: for i in range(len(arr),0,-1): print(arr[:i])
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2]
[0, 1]
[0]

arr[:None] means 0 from the end, and usually is sufficient.

Keep in mind the arr[:i] translates to arr.__getitem__(slice(None,i,None)). The : syntax is short hand for a slice object. And the slice signature is:

slice(stop)
slice(start, stop[, step])

slice itself is pretty simple. It's the __getitem__ method that gives it meaning. You could, in theory, subclass list, and give it a custom __getitem__ that treats slice(None,0,None) as slice(None,None,None).

Upvotes: 1

Sida Zhou
Sida Zhou

Reputation: 3705

Had a brain freeze, but this would do:

arr=[0,1,2,3,4,5]
for i in range(0,3):
    print arr[:len(arr)-i]

Although I still wish python had nicer syntax to do these kind of simple tasks.

Upvotes: 1

Alexander
Alexander

Reputation: 109546

for i in xrange(0, 3):
    print arr[:(len(arr) - i)]
# Output
# [0, 1, 2, 3, 4, 5]
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3]

Upvotes: 5

Daniel
Daniel

Reputation: 42758

You can use None:

arr=[0,1,2,3,4,5]
for i in range(0,3):
    print arr[:-i or None]

Upvotes: 7

Related Questions