Search code examples
pythoncounter

How to print the first ten elements from Counter?


With this code, I print all the elements sorted with the most common word used in the textfile first. How do I print only the first ten elements?

with open("something.txt") as f:
    words = Counter(f.read().split())
print(words)

Solution

  • From the docs:

    most_common([n])

    Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

    I would try:

    words = Counter(f.read().split()).most_common(10)
    

    Source: here