JGrazza
JGrazza

Reputation: 75

How to return a list of strings that is a certain length?

What I'm trying to do is create a program that returns a list of strings that are a certain length. I have a program made but I feel that it's extremely off

def lett(lst,n):
res = []
for a in range(1,len(lst)):
               if a == n
                   res = lst[a]
return res

what I want is to take the list and return all the words that are the length of n so if I were to do lett(["boo","hello","maybe","yes","nope"], ) it would return ['boo','yes']

thanks!

Upvotes: 2

Views: 169

Answers (3)

sunkehappy
sunkehappy

Reputation: 9091

def lett(lst, n):
    return [tmpStr for tmpStr in lst if len(tmpStr) == n]

Upvotes: 0

Volatility
Volatility

Reputation: 32300

Use the filter function

def lett(lst, n):
    return filter(lambda x: len(x) == n, lst)

This will return a list in Python 2. If you're using Python 3, it returns a filter object, so you might want to convert it to a list.

return list(filter(lambda x: len(x) == n, lst))

Upvotes: 2

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

Try this:

def lett(lst, n):
    return [x for x in lst if len(x) == n]

Or:

def lett(lst, n)
    return filter(lambda x: len(x) == n, lst)

Upvotes: 2

Related Questions