0

I'm working on a Python exercise at Codecademy and got stuck on what looks like a simple problem:

Write a function fizz_count() that loops through all the elements of a list. When the element is 'fizz', increment a counter called count. Then return the value of count.

My code:

def fizz_count(x):
  count = 0
  for i in x:
    if x[i] == 'fizz':
      count = count + 1
  return count

I get this error message:

An exception was raised for fizz_count(['fizz', 'buzz']): list indices must 
be integers not str

Everything is formatted exactly as shown. I can't figure out where the error is.

1
  • 1
    The error tells you exactly where the error is - if the list index must be an integer, but is actually a string, then i is a string. Why not print i to find out why? Commented Jun 21, 2014 at 9:04

3 Answers 3

4

If x is a sequence of elements, when you do

for i in x:

you are looping through the elements of x, not through indexes.

So when you do

x[i]

you are doing

x[element]

which makes no sense.

What can you do?

You can compare the element with 'fizz':

for element in x:
    if element == 'fizz':
        # ...
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I just figured it out. This is not C++ :P Thanks!
3

You are passing in a list ['fizz', 'buzz']) so i is equal to fizz or buzz not an integer. Try if i =="fizz"

def fizz_count(x):
  count = 0
  for i in x:
    if i  == 'fizz': # i will be each element in your list
      count = count + 1
  return count

Comments

0

When you used { for i in x } then here 'i' is the item of the list and not an index. Hence,

Corrected Code is:

def fizz_count(x):
  count = 0
  for i in x:
    if i == 'fizz':
      count = count + 1
  return count

print fizz_count(['fizz', 'buzz'])

OUTPUT

1

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.