Subindexing array, alternative to `getfield.(A,:2)`?

I want to get an array containing e.g. the second field from all objects in array A.

So far I’ve found:

getfield.(A,:2)

or

[ a[2] for a in A ]

Is there a better or more “Julian” way? I was hoping for A.[2].

You can do getfield.(A, [2]) too, but isn’t the comprehension more readable?

You don’t need :2 or [2], 2 should be enough.

Also, a[2] will only work for tuples.

1 Like

I’m confused as you ask about subindexing, but are using getfield(A, :2) instead of getindex(A, :2).
Do you have an array of composite types?

I had an issue with subindexing and tried A[:][2] - This doesn’t get the second element of each element in A, but just the second element of A.
Edit: This is of course expected, as indexing an array with a range returns an array - in this case the whole array. Still, i would like to have some easy syntax for subindexing.

It sounds like you want getindex.(A, 2) if it is an array of arrays or tuples?

There’s been some discussion of implementing A.[2] syntax (https://github.com/JuliaLang/julia/issues/19169), but nothing has been resolved at this point, and dot calls with getindex work fine.

If you have an array of composite types, getfield.(A, 2) should work, but will be slower than a comprehension since the compiler can’t really optimize getfield calls, last I checked. (In principle, we could implement optimizations for something like getfield.(A, Val{2}()) so that the value 2 is known by the compiler, but this doesn’t seem to have been done.)

Sorry for the confusion, it’s an array of tuples in this case. I used subindexing for lack of a better word. I tried playing around with composite types as well, that’s were I went with getfield instead of getindex.

@dpsanders I agree that the comprehension is more readable. Although having a descriptive function name as a visual anchor also appeals to me.

@stevengj Thanks! I tried searching for such an issue to read up on but didn’t know the terminology.

Thanks for the answers!

Note, however, that the getindex.(a, 2) version could be faster because it can fuse with other dot calls.

4 Likes

Thanks for pointing that out. For anyone interested there’s a timely blog entry on loop fusion in Julia.