14

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.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
shaarr
  • 141
  • 1
  • 1
  • 4

5 Answers5

24

I would use a list comprehension:

def by_size(words, size):
    return [word for word in words if len(word) == size]
Ben
  • 6,687
  • 2
  • 33
  • 46
7
return filter(lambda x: len(x)==size, words)

for more info about the function, please see filter()

h2ku
  • 947
  • 8
  • 11
user2717954
  • 1,822
  • 2
  • 17
  • 28
4

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']
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
丁东阳
  • 59
  • 3
3
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']

R A Khan
  • 187
  • 4
  • 12
  • I think this is nice. If I want to enforce my precondition which is,"words is a list of strings. size is a positive int", is there anything I need to modify? – shaarr Nov 02 '14 at 09:07
  • Yes , you can enforce your precondition with the modification like: **if size>-1 and if isinstance(word, str):** – R A Khan Nov 02 '14 at 10:05
0

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.

natus
  • 74
  • 2
  • 8