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

Looping over string items in a list and checking the first index of the string item

This is the first time I post a programming question anywhere, ever. Fingers crossed I get a useful answer.
I’m new to programming (3rd month learning), so I’m not sure if what I’m trying to do is possible and have tried reading a lot of articles and answers to questions here and on many other places, but I can’t seem to find an answer.

What I’m trying to do is to loop over a list of strings to count how many strings start with a certain letter/character. I have created this sample code for my practice, I hope it elucidates what I’m trying to do:

myList = ['Dog', 'Cat', ' Horse', 'Duck', 'Camel', 'Elephant', 'Donkey']

for item in myList:
    startsWith_D = 0
    startsWith_C = 0
    if item[0] == 'D':
        startsWith_D += 1
    elif item[0] == 'C':
         startsWith_C += 1
print(startsWith_D, startsWith_C)

I’m hoping the answer would help me understand how loops work in python better

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

>Solution :

Notice that you are setting the values to 0 every time within the loop. Put those outside the loop …

myList = ['Dog', 'Cat', ' Horse', 'Duck', 'Camel', 'Elephant', 'Donkey']

startsWith_D = 0
startsWith_C = 0

for item in myList:
    if item[0] == 'D':
        startsWith_D += 1
    elif item[0] == 'C':
         startsWith_C += 1
print(startsWith_D, startsWith_C)
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