X Length - Help Understanding Why My Code Doesn't Work

Hi CodeCademy Community!

My code vs. CodeCademy’s solution are very similar, but with a key difference and I’m having a hard time understanding why the code behaves after making slight tweak. My answer makes a new list and splits every word into that new list, while it looks like CodeCademy’s answer does that same mechanism but doesn’t bother creating a list.

My questions: why does my “list” solution not work? What pieces are missing to be able to iterate through list and return length from it?

Is there an advantage here to using a string vs. list?

My Answer:

def x_length_words(sentence,x):
  lst_of_every_word = [sentence.split()]
  for i in lst_of_every_word:
    if len(i) < x:
      return False
    else:
      return True

print(x_length_words("i like apples", 2))
# should print False
print(x_length_words("he likes apples", 2))
# should print True

CodeCademy’s Answer:

def x_length_words(sentence,x):
  lst_of_every_word = sentence.split()
  for i in lst_of_every_word:
    if len(i) < x:
      return False
    else:
      return True

print(x_length_words("i like apples", 2))
# should print False
print(x_length_words("he likes apples", 2))
# should print True

Link to exercise

Thanks in advance for the opportunity to learn!

Trevor

.split() already returns a list, by so wrapping it in another list, you get nested lists:

lst_of_every_word = [sentence.split()]
print(lst_of_every_word)
2 Likes

Wow thanks, I knew I had missed a key piece regarding .split() during the lesson. This helps out a lot.

Thanks!

1 Like

Why do you have a loop if you’re only going to make one iteration…?