2

Can anyone please explain how to output the rightmost index from several most-same-values indexes in the list?

my function:

def last_index(xs,key):
i = 0
    for i in range(len(xs)):
        if xs[i] == key:
            if i != len(xs):
                return i            
            else: 
                return 'None'

for example,

xs = [3,4,5,6,4,4,5]                
key = 4                              

the rightmost index output should be a single 5. But I got all three all them which are index 1,4,5. Thanks for the help, and sorry I'm totally new.

what if the input as strings like:

 xs=[True,True,True,False]
 key = True

I believe the output is 2?

markzzzz
  • 89
  • 1
  • 6

6 Answers6

3

This simple solution should do:

def last_index(xs, key):
    index = None
    for i in xrange(len(xs)):
        if xs[i] == key:
            index = i  # override index, result in the rightmost index of key
    return index  # returns None if key is not on the list

A more efficient way to do this is by iterating from the end to start and returning the index when key is found, in worst case - key is not found and we will iterate over the entire list.

Check out the more efficient version:

def last_index(xs, key):
    index = None
    for i in xrange(len(xs)-1, 0, -1):  # iterate from last item to first
        if xs[i] == key:
            index = i
            break  # found the rightmost index, exit the loop
    return index

Notice you should prefer using xrange over range (unless in python 3 where range equals to xrange), also to avoid an edge case when items involve different types see Andriy's answer.

Community
  • 1
  • 1
Forge
  • 6,538
  • 6
  • 44
  • 64
1

You can try a function like this

def last_index(xs,key):
    index = -1
    for i in range(len(xs)):
        if xs[i] == key:
            index=i           
    if index!=-1:
        return index
    else:
        return "none"

This will get the last index that matches your key. If there is none will return "none".

Hadrián
  • 334
  • 1
  • 2
  • 9
1

This should do the trick:

def last_index(xs,key):
    index = -1
    for i in range(len(xs)):
        if xs[i] != key:
            continue
        else:
            index = i
    return index if index != -1 else 'None'
Ian
  • 30,182
  • 19
  • 69
  • 107
1

Traverse xs in reverse order and return first matched value, with reversed function:

def last_index(xs,key):
    for i in reversed(range(len(xs))):
        if xs[i] == key:
            return i


xs = [3,4,5,6,4,4,5]
key = 4
print last_index(xs, key) # output: 5

xs=[True,True,True,False]
key = True
print last_index(xs, key) # output: 2
print last_index(xs, 2) # output: None

NOTE#1

You can use xrange instead of range it would give you better performace and won't be deprecated since python3, see Should you always favor xrange() over range()? for more info.

Your comparison may be improved by replacing

if xs[i] == key

to

if xs[i] == key and type(a) == type(b)

NOTE#2

To avoid bug when your 1 == True would return you index of True however you wanna index of 1 whicn not exist, compare result for both if conditions when xs and key have values below

xs=[True,True,True,False]
key = 1

See Strict comparison for more information about that behaviour.

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • Just to note, if he is using python 3 then he has to use range (xrange does not exists anymore in python 3). – Hadrián Feb 27 '16 at 17:06
0

You can reverse the list and then use .index():

index = xs[len(xs) - list(reversed(xs)).index(key)]

By the way, in your second list, True and False are booleans, not strings.

zondo
  • 19,901
  • 8
  • 44
  • 83
0

Iterate from behind like this:

def last_index(xs,key):
    i= len(xs)-1
    while i >=0:
        if xs[i] == key:
            return i
         i -= 1

This way if the key does not exist the function will return the none value

Spyke
  • 114
  • 4