I am trying to understand why first code run only once vs second code is running until it checks all the items in the list.
1.
def get_word_over_10_char(list_of_words):
for word in list_of_words:
if len(word) > 10:
return word
else:
return ""
for word in list_of_words:
if len(word) > 10:
return word
return ''
word_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']
Trying to return a word if length is more than 10, and return empty string if less than equal to 10.
CodePudding user response:
How are the items in your list ordered? Because the when the return
statement in a function is called, the function returns the argument and stops. In the first piece of code, either the return
in the if
clause or the else
is called after the first item in list_of_words
, so the function stops there. In the second piece of code, the return word
statement is only called once a word longer than 10 characters is found. From how you describe the problem, I reckon that the last item in your list_of_words
is longer than 10. So with the second piece of code, you notice that that word is not returned, while you do not notice the empty strings not being returned.
CodePudding user response:
As Timo explained in his answer, function stops when you use return
. In order to get all the elements with more than 10 characters, you need to create a list with these words before using return
:
def get_word_over_10_char(list_of_words):
more_than_10 = []
for word in list_of_words:
if len(word) > 10:
more_than_10.append(word)
if len(more_than_10)==0:
return "Nothing longer than 10"
return more_than_10
word_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']
print(get_word_over_10_char(word_list))
A more pythonic second version using list comprehension to create more_than_10
:
def get_word_over_10_char_v2(list_of_words):
more_than_10 = [word for word in list_of_words if len(word) > 10]
if len(more_than_10)==0:
return "Nothing longer than 10"
return more_than_10
word_list = ['soup', 'parameter', 'intuition', 'house-maker', 'fabrication']
print(get_word_over_10_char_v2(word_list))