Bob
Bob

Reputation: 756

Deleting Index of leading 0s in bit array

I am trying to delete the leading 0's for a bit array I created out of a list. What I am trying to do is:

while binPayload[0] == 0:
    del binPayload[0]

However the interrupter is throwing:

IndexError: list assignment index out of range.

Upvotes: 1

Views: 100

Answers (2)

Óscar López
Óscar López

Reputation: 236150

Try this:

import itertools as it
a = [0, 0, 0, 0, 1, 1, 1, 1]
list(it.dropwhile(lambda x: x == 0, a))
=> [1, 1, 1, 1]

Upvotes: 1

grc
grc

Reputation: 23585

You should check that the list is not empty each time before indexing it. Since an empty list is considered false, you can simply do:

while binPayload and binPayload[0] == 0:
    del binPayload[0]

Upvotes: 2

Related Questions