If I use `in` do I need to set something to return `True`?

Hello!

I know that I’ve tried to solve it differently by going at it differently and not using “in” for both parameters and I’ve understood how to answer the question.

However, I’m having trouble understanding why the code I’ve written always seems to be returning an empty list.

def common_letters(string_one, string_two):
  common_lst = []
  for char1 in string_one:
    for char2 in string_two:
      if char1 == char2 and char1 not in common_lst == True:
        common_lst.append(char1)
  return common_lst

**Edit:

I’ve also tried changing the indentation of the return common_lst with no avail. So far I understand the concepts taught in this course pretty well, but for some reason I always struggle with indentation!

Unnecessary to write == True.

Is it really necessary to iterate both strings? Consider that in is a sort of iterator as it seeks membership. Iterating over one string (either one) and searching in the other will certainly detect any matches.

Hi mtf,

Could you please clarify what you mean regarding in?

in returns True or False all by itself. You don’t need to add == True.

my_str = 'abcde'
print('abc' in my_str)
print('xyz' in my_str)

Output:

True
False

Incidentally, due to operator precedence, and the way chaining works, your expression won’t work as you expect:

print('xyz' not in my_str ==  True)

Output:

False

The chained expression is evaluated as follows:

('xyz' not in my_str) and (my_str ==  True)

… which returns False, since the second term returns False.

4 Likes

Woah. Took me a good minute to see that there was comparison chaining there even after you said it. That’s pretty surprising. I’d never write that, but I’d also never spot it by only reading it.

1 Like

Owing that in (membership) and == (identity) have equal precedence, operations occur from left to right

'xyz' not in my_str  => True
True == True         => True

…no
but that’s how I would first read it, too.

1 Like
>>> my_str = 'abcdef'
>>> 'xyz' not in my_str
True
>>> 'xyz' not in my_str == True
False
>>> 

I stand corrected, thank you.

1 Like