Julia equivalent of the Python `slice` class

In Python I can store an index range into a variable and reuse it. In particular, I can store a range with implicit begin-at-0 and end-at-end-of-list extremas.

How do I do the following in Julia:

my_list = [1,2,3,4,5,6,7,8,9,0]
my_boring_slice = slice(2,8,3)
my_interesting_slice = slice(3,None,None)
some_sublist = my_list[my_boring_slice]
the_sublist_I_really_want = my_list[my_interesting_slice]

I know I can define my own slice type, and I think I understand what methods I need to define in order for it to work on most Array types. But I am hopeful there is some obvious class in Base that already implements this. A cursory look through the docs and some googling/ducking did not really help.

Just my_list[4:end]? Ok, I get you want to pull out the 4:end to re-use it, but note that there is zero cost to constructing that thing. Unlike Python, our : range syntax works outside of indexing. You can just do my_boring_slice = 3:3:8 or my_interesting_slice = 4:length(my_list) or even my_whole_dimension = (:).

Julia’s slices are just arrays of integers. That’s it. There is a very simple package that you can use — EndpointRanges.jl — that can give you an end that works outside of indexing and dynamically matches the arrays it indexes into.

3 Likes

Thanks, EndpointRanges is exactly what I needed! I do have a vague sense of discomfort that this is not in Base, but that is probably just because I was burnt by Javascript.

Is EndpointRanges.jl still necessary? You can also index from the beginning of the array with begin, for use with OffsetArrays.jl and such.

using OffsetArrays

a=OffsetArray([1:11;],-6)
#11-element OffsetArray(::Vector{Int64}, -5:5) with eltype Int64 with indices -5:5:

a[3] #9 
a[begin+2:3:end] # [3,6,9]
1 Like

I can not store begin+2:end in a variable. I specifically need a slice object to be stored in a variable, generated programmatically or modified.

1 Like