Search code examples
python-3.xenumerate

python print first n lines of string


I'm wondering how to print the first n lines of string in python here is my code:

for word, numbers in enumerate(sorted):
        print(word,':',numbers)

The output looks like following. how can I print just first 10 lines of these string? I've tried to use range, but it only prints True or False...

0 : ('the', 1577)
1 : ('and', 1080)
2 : ('of', 761)
3 : ('to', 734)
4 : ('a', 720)
5 : ('in', 550)
6 : ('it', 451)
7 : ('was', 432)
8 : ('his', 405)
9 : ('he', 381)
10 : ('I', 365)
11 : ('Scrooge', 361)
12 : ('that', 346)
13 : ('with', 312)
14 : ('you', 254)
15 : ('as', 229)
16 : ('said', 221)
17 : ('for', 209)
18 : ('had', 207)
19 : ('him', 198)
20 : ('not', 193)

Solution

  • If you only want to get the 10 first elements of the list then just slice the list accordingly

    for word, numbers in enumerate(sorted[:10]):
            print(word,':',numbers)