how to get INDEX count, or last number of Index

Cameron Simpson cs at cskk.id.au
Wed May 23 18:31:23 EDT 2018


On 23May2018 23:14, Mark Lawrence <breamoreboy at gmail.com> wrote:
>On 23/05/18 22:56, Rob Gaddi wrote:
>>On 05/23/2018 02:51 PM, asa32sd23 at gmail.com wrote:
>>>s = "kitti"
>>>
>>>0,1,2,3,4
>>>k,i,t,t,i
>>>
>>>how do i retrieve '4'. i know i can do a len(s)-1, but i assume 
>>>there is a function that gives me last number of index
>>>
>>
>>Not sure I'm following your question; len(s)-1 is much faster than 
>>enumerating over the string just to get the last index.
>
>-1 is even faster.

For fetching the last element, sure. But possibly the OP needs to know the 
actual index. Example use case:

  chars = []
  last_per_char = {}
  for char in "some string here with letters and stuff":
    chars.append(char)
    last_per_char[char] = len(chars) - 1

That's only slightly contrived, but there are plenty of real world situations 
where you accrue data and need to know the absolute position of the latest 
instance of particular records.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list