2

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]

4 Answers 4

7

You can use None:

arr=[0,1,2,3,4,5]
for i in range(0,3):
    print arr[:-i or None]
Sign up to request clarification or add additional context in comments.

4 Comments

bah you beat me ... barely :P
And here I was cooking up something with itertools.chain([None], range(-1, -3, -1)) -- This is significantly better though I would still recommend the branch I think.
even a branch like this is much clearer print arr[:-i ] if i > 0 else arr
I just wish these things were more readable to normal people :p
5
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]

Comments

1

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.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.