I was looking at this python code that I need some explanation with:
arr = [0, 0, 0, 0, 1, 2, 3, 4,5]
arr = arr[next((i for i, x in enumerate(arr) if x != 0), len(arr)):]
This code would remove the leading zeroes from the array, I am trying to understand how it works. I understand that we created an iterator that would iterate over all elements of arr
but 0 values, and next would iterate only till length of array (not inclusive).
But how are these indices returned by next, combine to form an array?
Let's look at the code step by step. You want to slice off the initial zeros. If you knew the index of the first non-zero element, n
, the expression would look like
arr = arr[n:]
That's basically what we have here, with n = next((i for i, x in enumerate(arr) if x != 0), len(arr))
.
In general, the two-arg form of next
will return the second argument as a marker instead of raising a StopIteration
should the iterator run out. That's what the len(arr)
is for. If all the elements are zero, the expression becomes
arr = arr[len(arr):] # obviously empty
If there is a non-zero element, the next
call will find its index (enabled with enumerate
), and return it.