I am trying to count the occurrence of the name in a name_list with letter 'i' as their second letter using a nested loop.
def print_count(names_list):
for name in names_list:
count = 0
for i in range(len(name)):
if name[i] == 'i' and i == 1:
count = count 1
print(count)
names = ["Cody", "Baldassar", "Delilah", "Vinnie", "Leila", "Zac", "Aiden", "Zaynab"]
print_count(names)
My expected output should be: 2 but i got 0 instead.
CodePudding user response:
You are setting count to zero for every name because you placed count=0
inside the loop that loops over the names. The way it is now, the count that is printed only contains the count of the last name in the list.
If you move it out of the loop your code will work.
CodePudding user response:
You can express that simply and in a manner that is fast:
>>> len([s for s in names if s[1:].startswith('i')])
2
Why?
The argument of len
is a list comprehension. It is the original list, filtered by "must have a second letter, and that second letter must be 'i'
".
>>> [s for s in names if s[1:].startswith('i')]
['Vinnie', 'Aiden']
CodePudding user response:
Add count = 0
above the for loop. Otherwise, you reset it to zero each time. In addition, you do not need the second loop.
def print_count(names_list):
count = 0
for name in names_list:
if name[1] == 'i':
count = 1
print(count)
names = ["Cody", "Baldassar", "Delilah", "Vinnie", "Leila", "Zac", "Aiden", "Zaynab"] print_count(names)