python: select a sublist with a list length limit
Question: > players = [ a long list of (id, float) tuples with each id unique, order by
> highest float]
>
> on_teams = [ a list of unique ids, every on_teams id is also in the players
> list]
    
    
    picked = set(on_teams)
    best_remaining = []
    for best_player in players:
        if best_player[0] not in picked:
            best_remaining.append(best_player)
        if len(best_remaining) == 5: break
    

When I use six lines of code to do a simple thing, such as "get the five best
remaining players", I wonder if there isn't a more elegant, pythonic solution.
It's a simple problem, no doubt, but is there a better way to code it?

UPDATE: My code run 100,000 times, runs in 0.24 secs. When I run:

    
    
    best_remaining = [(id, float) for id, float in players if id not in picked][:5]
    

The code runs in 4.61 secs (100,000x). So the code looks and scans nicer, but
it create the whole list then slices it. So now my question is a little
different. With speed as a constraint, is there a better way to code up the
search for the '5 best remaining players`?

UPDATE:

    
    
    best_remaining = list(islice((p for p in players if p[0] not in picked), 5))
    

This code runs trivially longer than my code. To me at least, it has the value
of a list comprehension. And best of all, it shows me a good place to work on
my code habits. Thanks


Answer: Use a generator, and then `islice` it to a max of 5 results...

    
    
    from itertools import islice
    picked = set(on_teams)
    players = list(islice((p for p in players if p[0] not in picked), 5))
    

