How to return elements from a list that have a certain length?

shaarr picture shaarr · Nov 2, 2014 · Viewed 19.3k times · Source

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 like this.

by_size(['a','bb','ccc','dd'],2] returns ['bb','dd']

def by_size(words,size)
    for word in words:
        if len(word)==size:

I'm not sure how to continue from this part. Any suggestion would be a great help.

Answer

Ben picture Ben · Nov 2, 2014

I would use a list comprehension:

def by_size(words, size):
    return [word for word in words if len(word) == size]