Hi Everyone.
I'd appreciate your help writing better code.

I have a list of ~1000 values:

list_of_values = [0x123D, 0x844F, 0x33E9, ....., 0xFFFF, 0xFFFF, 0xFFFF]

The last values in the list will always be 0xFFFF, but I don't know how many exactly.
What I want is to get rid of all those trailing 0xFFFF values to shorthen the list.

I have a solution which works, but I feel isn't quite Pythonic enough:

list_of_values.reverse()     # Start at the end of the list

for index, value in enumerate(list_of_values):
    if value != 0xFFFF:     # The first useable value
        list_of_values = list_of_values[index:]
        list_of_values.reverse() # Retun list ordering (or use [::-1] in previous line)

This code works well, but can it be done better? I was thinking about using the any() function, but I haven't found a way to break and get the index using it.

Thanks again for your help :-)

4 Years
Discussion Span
Last Post by valorien

Maybe this:

mylist = [0x123D, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
newlist = (mylist[:mylist.index(0xFFFF)])[::-1]

If only value 0xFFFF has duplicate vaules,then set() would be fine.

>>> lst = [0x123D, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
>>> set(lst)
set([4669, 13289, 33871, 65535])

If you want to keep duplicate vaules before 0xFFFF,lety say 0x844F and 0x844F.
Then set() is not way.

Edited by snippsat


My Apologies, I forgot to mention that 0xFFFF can also appear anywhere in the list, e.g.:

[0x1234, 0x4567, 0xFFFF, 0x44DD, 0xFFFF, 0x33E2,.....,0xFFFF, 0xFFFF, 0xFFFF]

I need all the values in the list besides the trailing 0xFFFF ones. I can't use set() since I require all list values.

Thank you for your help.


Then simply do something like this:

mylist = [0x123D, 0xFFFF, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF]
newlist = (mylist[:mylist.index(0xFFFF, 2)])[::-1]

Edited by ZZucker


Again - There is an unknown amount of 0xFFFF's in the list. I don't know how many.
I only want to remove the last ones.

Also, what does

index(0xFFFF, 2)


import itertools

def cleanup(lst):
    def drop(x):
        return lst[x] == 0xFFFF
    return  lst[:next(itertools.dropwhile(drop, reversed(range(len(lst)))))+1]

print cleanup([0x123D, 0x844F, 0x33E9, 0x1234, 0xFFFF, 0x2342, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF])

Edited by pyTony


There is no need to reverse the list twice as you can use -1 in a for loop and start at the back end. Other than that, you have to look at all elements from the back of the list to the first non-0xFFFF however you do it.


You're right wooee, using [::-1] would be better, thanks.

PyTony, I haven't tested your solution yet.
If it's much faster than mine, that's excellent - Though I personally find it less readable, but maybe that's just me.

Thanks again everyone :-)!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.