How to get items from a list based on specific item in Python

Advertisements

I have below list

l = ['7E', '00', '10', '97', '9A', '00', '13', 'A2', '00', '41', 'B6', '13', '58', 'FF', 'FE', '41', '50', '00', '01', '28']

From above list, I want to extract 41 B6 13 58, which always comes after 00 13 A2 00 and is always length 4.

I thought of extracting this based on the index of 00 (just before 41) but there can be many 00 in the list so this will not be always correct.

So I have to make sure its always 00 13 A2 00 and then get the index of 00 (which is after A2) and from this index extract next 4 items which should be the final output. But I am unable to decide how to go for it. Can anyone please help.

>Solution :

for i in range(0, len(l)-8):
    if l[i:i+4] == ['00', '13', 'A2', '00']:
        return l[i+4:i+8]

So what we are doing: looking linearly for those four given values (indices i, i+1, i+2, and i+3), and if we find them, we take the next four values from the list – indices i+4, i+5, i+6, and i+7.

Leave a ReplyCancel reply