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:
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))