I'm trying to return words that have a specific length.
This is my code so far. words
is a list and size
is a positive integer.
def by_size(words, size)
for word in words:
if len(word) == size:
I'm not sure how to continue. by_size(['a', 'bb', 'ccc', 'dd'], 2)
should return ['bb', 'dd']
. Any suggestions would be of great help.
The len() function for getting the length of a list. Python has a built-in function len() for getting the total number of items in a list, tuple, arrays, dictionary etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.
Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function.
Description. Python list method len() returns the number of elements in the list.
I would use a list comprehension:
def by_size(words, size):
return [word for word in words if len(word) == size]
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With