Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of list[-1] in Python

I have a piece of code here that is supposed to return the least common element in a list of elements, ordered by commonality:

def getSingle(arr):
    from collections import Counter
    c = Counter(arr)

    return c.most_common()[-1]  # return the least common one -> (key,amounts) tuple

arr1 = [5, 3, 4, 3, 5, 5, 3]

counter = getSingle(arr1)

print (counter[0])

My question is in the significance of the -1 in return c.most_common()[-1]. Changing this value to any other breaks the code as the least common element is no longer returned. So, what does the -1 mean in this context?

like image 891
kratosthe1st Avatar asked Dec 01 '22 10:12

kratosthe1st


1 Answers

One of the neat features of Python lists is that you can index from the end of the list. You can do this by passing a negative number to []. It essentially treats len(array) as the 0th index. So, if you wanted the last element in array, you would call array[-1].

All your return c.most_common()[-1] statement does is call c.most_common and return the last value in the resulting list, which would give you the least common item in that list. Essentially, this line is equivalent to:

temp = c.most_common()
return temp[len(temp) - 1]
like image 58
Woody1193 Avatar answered Dec 25 '22 09:12

Woody1193