Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Membership

Marya Kamali
Marya Kamali
580 Points

what's wrong ? int obj is not iterable?

Why my code doesn't work?

counts.py
# You can check for dictionary membership using the
# "key in dict" syntax from lists.

### Example
# my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
# my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
# members(my_dict, my_list) => 2
def members(my_dict, my_list):
  numb=0
  for key in my_dict:
    for i in len(my_list):
      if key == my_list[i]:
        numb+=1

2 Answers

Seth Reece
Seth Reece
32,867 Points

Hi Mary,

In this challenge you want to loop through each item in the list, then check to see if it is a key in the dict. The integer object is not iterable comes from the line "for i in len(my_list):" len(my_list) will return an integer. e.g. 4. you need a list or dict etc to iterate. e.g. 1, 2, 3, 4. Also your function needs to return something. Don't forget to return numb at the end. To help with the challenge:

def members(my_dict, my_list):
  numb=0
  for i in my_list:
    if i in my_dict:
      numb+=1
  return numb
Marya Kamali
Marya Kamali
580 Points

I thought that list are only searchable by their indices ... thanks

len(my_list) is just a single number so there's nothing to loop over. What you need is a list of numbers from 0 to len(my_list). Typically you would use xrange, but I haven't found that to be available here, so try

for i in range(0, len(my_list)):
Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

xrange is Python 2. The site is based on Python 3 coding. range behaves as the Python2 xrange

I was not aware of that. Thanks for clarifying.