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

zakaria arr
zakaria arr
6,347 Points

A weird and puzzling problem!!

I was revisiting some python courses to just brush up on them and I stumbled on this challenge. The challenge is to Write a function named members that takes two arguments, a dictionary and a list of keys. Return a count of how many of the items in the list are also keys in the dictionary.

and this was the I wrote

# 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

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}

my_list = ['apples', 'coconuts', 'grapes', 'strawberries']



def members(the_list, the_dict):
  x = 0
  for item in the_dict:
    if item in the_list:
        x = x + 1
    return x

# That function only gives one 

members(my_dict, my_list)

This code for some reason does not yield the desired outcome of 2. It gave one. so I tested the code inside the function and funnily enough it this.

my_dict = {'apples': 1, 'bananas': 2, 'coconuts': 3}
my_list = ['apples', 'coconuts', 'grapes', 'strawberries']
x = 0
for item in my_dict:
    if item in my_list:
        x = x + 1
        print(x)

it gave this

1
2

Can Anyone explain this weird phenomena? Thank In Advance.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Your return statement is indented too far and is inside the for loop making it return after the first iteration. It will always return "1".

Unindent the return.

zakaria arr
zakaria arr
6,347 Points

Thanks well spot that it was subtle.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

I would also recommend increasing your indent to 4 spaces instead of 2. Four is the PEP-0008 recommended amount.