0

As we know that enumerate function can be use to find the in index of a value in list or hashmap. My question is can we specify the ending index of list. As the code is provided if anyone can help me to solve this problem. I will be very thankful to him

[i for i, key in enumerate(sorted_d) if key[1] == sortedVotes[0][0]]

UsmanMaan
  • 56
  • 5

2 Answers2

0

you can use a list slice.

ending_index = 5
[i for i, key in enumerate(sorted_d[:ending_index+1]) if key[1] == sortedVotes[0][0]]

I added 1 because the end of a slice is not inclusive.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

What do you mean by 'ending index of list'? If index of last element, then you may use

i_last = len(sorted_d) - 1

If you want to obtain the last item specially from 'enumerate' you may use the following code

i_last, value_last = None, None
for i_last, value_last in enumerate(sorted_d):
    pass

Cleanest way to get last item from Python iterator