Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dynamic array access [:0] [duplicate]

I try to access an array dynamically in a loop like array[n-i:-i] and it works fine as long as i != 0. In case i==0 I have array[n:0], which I would expect to output array from n to the end but it returns nothing (None i guess). How to archive the expected behaviour?

like image 803
user2504380 Avatar asked Jul 02 '15 10:07

user2504380


1 Answers

Use None to slice to the end; Python then'll use len(array) as the endpoint. Use or to fall back to None when -i is 0:

array[n-i:-i or None]

Numeric 0 is considered false in Python boolean contexts. The or operator short-circuits; it returns the first operand if it is a true value, otherwise it'll evaluate the second operand and return that.

like image 101
Martijn Pieters Avatar answered Oct 29 '22 12:10

Martijn Pieters