Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list.count() method returning count + 1 for the first value in iterable

I was working on one problem while I encountered this problem. Let me explain through a simple example:

a = ['hello', 'world']
print(a.count('hello')) #prints 1 correctly

But…

a = "hello world"
for i in a.split():
    print(a.count(i))

#prints
#2 -> for 'hello' which is wrong, one more than actual value
#1 -> counts of elements from 2nd onwards are correct

If I split it before, it works perfectly:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = 'hello world'
a = a.split()
for i in a:
    print(a.count(i))

#correctly prints
1
1

So I think the issue only happens when I use the split method directly in the for loop, but I’m not sure why.

Edit:

I rechecked it, and its printing wrong values for long statements, specifically for this one. Please check using this statement below:

"how many times does each word show up in this sentence word times each each word"

Edit 2:

Even though I was splitting the string in for loop directly, it did’t change the original string and I was using count method on original string inside the for loop, which caused the error and the ‘how’ to show up two times.

Thanks to the user Bobby, for correctly pointing out.

>Solution :

In your first example a has never been updated. Even in the for loop, you split a but that didn’t update a. You can verify this directly:

a = "hello world"
for i in a.split():
    print(a)
    print(a.count(i))

If you want the split string you need to save that to a variable like you did in the first example. You can do this within the for loop if you want:

a = "hello world"
for i in b:=a.split():
    print(b.count(i))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading