11

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?

Woody1193
  • 7,252
  • 5
  • 40
  • 90
kratosthe1st
  • 201
  • 1
  • 2
  • 7
  • When I run this i get `4`, which is the correct answer. What exactly is your question? – Patrick Haugh Sep 18 '18 at 21:58
  • 8
    `[-1]` means the last element in a sequence, which in this is case is the list of tuples like `(element, count)`, order by count descending so the last element is the least common element in the original collection. – khachik Sep 18 '18 at 22:00
  • 1
    Possible duplicate: https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation – Patrick Haugh Sep 18 '18 at 22:00
  • See [How to handle “Explain how this ${code dump} works” questions](https://meta.stackoverflow.com/questions/253894/how-to-handle-explain-how-this-code-dump-works-questions) on [meta] -- or, similarly, [How to deal with questions of the type "I don't understand how this code works?"](https://meta.stackoverflow.com/questions/278797/how-to-deal-with-questions-of-the-type-i-dont-understand-how-this-code-works); in general, such questions are too broad to be on-topic here. By contrast, "*what does foo[-1] mean in Python?*" would specific enough to be on-topic here, but also a duplicate. – Charles Duffy Sep 18 '18 at 22:12
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – Gino Mempin Dec 03 '22 at 03:37

1 Answers1

31

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]
Woody1193
  • 7,252
  • 5
  • 40
  • 90