Search code examples
pythonlistenumerate

Getting the index of specific element in a list after slicing in python


Given a list of employees' scores. the employee with the highest score among the first k employees or the last k employees in the score list is selected. then removed from the list.

I want to get the real index for the selected element.

score=[5, 12, 15, 11, 15]
k=2
max_value = max(max(score[:k]), max(score[-k:]))
index=score.index(max_value)
print(index)
score.remove(score[index])
print(score)

the output is :

2
[5, 12, 11, 15]

the desired output:

4
[5,12,15,11]

The problem is index() will return the first occurrence. I know enumerate can be a solution somehow, but I am not able to apply it in my code.


Solution

  • Thank for editing your question. I think I now understood what you want. Of course this can be shorten by removing some variables. I left them there to make the code more clear.

    score = [5, 15, 12, 15, 13, 11, 15]
    
    k = 2
    
    first = score[:k]
    last = score[-k:]
    
    cut = [*first, *last]
    max_value = max(cut)
    
    for i in range(len(score)):
        if (i < k or i >= len(score)-k) and score[i] == max_value:
            score.pop(i)
            break
    
    print(score)