0

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?

3
  • what exactly do you think is wrong here ? exact same code executes to create [1 2 3 4 5] Commented Sep 23, 2019 at 3:51
  • It might be, but I still want to understand how it works. Commented Sep 23, 2019 at 3:56
  • Nevermind. I didn't read carefully. Answer coming up Commented Sep 23, 2019 at 3:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For some reason, I thought next would return an iterator, my bad. This is straightforward. I will mark it as answer for readers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.