0

Let's say I have a list with 0 or more elements, how can I return the amount of strings in it without using count() or other methods other than a while loop? I tried the code below but it keeps crashing.

values = ["one", "two", [], 6]

def count_str(values):
    index = 0
    while index <= len(values):
        if type(values[index]) == str:
            index += 1
    return index
1
  • The problem is that you use the same index for iterating over values, and to count strings... So when it's not a string, index does not change, and the loop never ends. Use two variables. Commented Aug 9, 2021 at 0:16

1 Answer 1

2

The issue is you got an infinite loop because you only increase the index when it is a string, given that not all instances are, the loop never finishes

try:

values = ["one", "two", [], 6]

def count_str(values):
  index = 0
  counter = 0
  while index <= len(values)-1:
    if type(values[index]) == str:
      counter += 1
    index += 1
  return counter

ans = count_str(values)
print(ans)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.