0

Please see the below code

def common_letters(string_one,string_two):
    letters_in_common = []
    for letter in string_one:
        for letter2 in string_two:
            if letter == letter2:
                letters_in_common.append(letter)
                return letters_in_common

returned = common_letters("hello", "loha")
print(returned)

The above code works, but only on the first iteration of the outer loop, hence my letters_in_common list only returns ['h'] when it should return ['h','l','l'], In JS the syntax is different and the loop works incrementally.

Am I misunderstanding how loops work in Python or is there a syntax level step I have not included?

p.s. I am aware that I could use the 'in' keyword etc but I wanted to try it with a loop first.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zack Amin
  • 514
  • 4
  • 12

1 Answers1

3

Your return is indented so that it is inside if. Presumably you want to return after you check every letter against every letter, which means return has to be outside the loops:

def common_letters(string_one, string_two):
    letters_in_common = []
    for letter in string_one:
        for letter2 in string_two:
            if letter == letter2:
                letters_in_common.append(letter)
    return letters_in_common

Sidenote: This will give a somewhat surprising result if there are multiples of a shared letter in both strings. If I wanted to find out just the shared letters, I would use set intersection:

def common_letters(string_one, string_two):
    return list(set(string_one) & set(string_two))
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Thanks, make sense and it is now working fine. May take me a little time to get used to indentation lines! – Zack Amin Sep 05 '21 at 11:16