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

Time:05-31

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

CodePudding user response:

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)
  • Related