Week 5: Python: Assignment: Exercise#1: Q7

no_of_words = 0
with open('sample text.txt', 'r') as file:
    for line in file.readlines():
        no_of_words += line.__len__()
no_of_words

Does the function __len__() return number of words or characters in the given string?

Yes. __len__() returns number of words or characters in the given string.
In fact, it can be used only for strings. While len() can be used lists, strings, etc.
I think __len__() is more efficient than len() when data is huge.

Does __len__() return words or characters?

When I execute this, I get characters, whereas I need words.

I think __len__() returns characters when applied to a string.
To get words for this question you can use the following code.

no_of_words = 0
with open('sample text.txt', 'r') as file:
    for line in file.readlines():
        no_of_words += len(line.split())
no_of_words
1 Like

Thanks @Mugdha!!

In fact, that is what I had used but the solution given had the __len__() function. So I wanted to clarify. Thank you very much!

1 Like

There’s not much difference between len() and __len__() but the latter works faster than the former.

1 Like

But __len__() mentioned in the solution gives number of characters whereas, the question is asking for number of words.

It depends on the input, if you’re using it with a string, you’ll get no. of characters, but if you use it on a list, it will get you number of strings/elements in that list