Reputation: 11
z=[1,2,","]
count=0
for i in z:
if (",") in z:
count+=1
print count
this python code counts all commas in list z
.Why? Answer is 3.when it should be one. One can test by changing elements.
If list element comma "," is deleted, program produces blank, not 2 commas as count.
Questions:
thanks
Upvotes: 1
Views: 102
Reputation: 1633
When you use if (",") in z
python checks if the comma is in your list and it will return true each time and when you delete the "," from the list it never produce true and the count would be zero so the correct version would be
z=[1,2,","]
count=0
for i in z:
if i == ',':
count+=1
print count
and also your print statement should not be in your for body
Upvotes: 0
Reputation: 510
Three times you checked whether ',' is in z. Yes it is. Yes it still is. Yes again. That's 3.
for i in z:
if i == ',':
count+=1
print count
Upvotes: 0
Reputation: 11039
The reason you are seeing 3 as your answer is because of this:
if (",") in z:
You are iterating across the list and for each element in the list you are checking if ','
is in the list z
, which it is. You count variable is incremented accordingly.
Upvotes: 0
Reputation: 113988
change it to
if (",") in i:
really you should use better names (i
typically refers to an index into an array or a integer count.. whereas you are iterating over the actual items in the list)
for item in z:
if (",") in item:
count+=1
print count
Upvotes: 2