I\'m trying to return words that have a specific length size.
The words
is a list and size
is a positive integer here.
The result should be
Assuming you want to use them later then returning them as a list is a good idea. Or just print them to terminal. It really depends on what you are aiming for. You can just go list (or whatever the variable name is).append within the if statement to do this.
Do you mean this:
In [1]: words = ['a', 'bb', 'ccc', 'dd']
In [2]: result = [item for item in words if len(item)==2]
In [3]: result
Out[3]: ['bb', 'dd']
def by_size(words,size):
result = []
for word in words:
if len(word)==size:
result.append(word)
return result
Now call the function like below
desired_result = by_size(['a','bb','ccc','dd'],2)
where desired_result
will be ['bb', 'dd']
I would use a list comprehension:
def by_size(words, size):
return [word for word in words if len(word) == size]
return filter(lambda x: len(x)==size, words)
for more info about the function, please see filter()