How do I get a list of indices of non zero elements in a list?


#1

a=[0,1,0,1,0,0]
[i for i, e in enumerate(a) if e != 0]
The above code snippet in python will give me indices viz:1,3

I was trying to figure out how to do it in kotlin in same ease.
Any pointers if it exists?


#2

val array = intArrayOf(0, 0, 1, 0, 1, 0, 0, 1)
print(array.indices.filterIndexed { _, i -> array[i] != 0 })

This is what I have got. Looks good though, but if anyone has better way to do it, please reply


#3

You can just use

val array = intArrayOf(0, 0, 1, 0, 1, 0, 0, 1)
print(array.indices.filtered { array[it] != 0 })


#4

It’s filter, not filtered

When doing Kotlin I often feel dirty creating local variables so I try to find ways to avoid creating local variables and this is what I came up with here:

intArrayOf(0, 0, 1, 0, 1, 0, 0, 1)
        .mapIndexed{i, v -> if(v != 0) i else -1}
        .filter { it >= 0 }

It would not be difficult to do your own extension method for this operation as well.


#5
listOf(0, 0, 1, 0, 1, 0, 0, 1).mapIndexedNotNull { i, n -> i.takeIf { n != 0 } }