Bob
Bob

Reputation: 1396

How to iterate through a list finding words of a Certain length?

Given a list for example,

F=['MIKE', 'BALL', 'FISH', 'BAT', 'BEAR', 'CAT', 'AT', 'ALLY']

How would I go about iterating through said list finding all words with a certain length inputted by the user? I thought it would be..

number=input("How long would you like your word to be?")
possible_words=[]
for word in F:
     if word(len)=number:
          possible_words+=word 

Upvotes: 0

Views: 2291

Answers (4)

Julien Grenier
Julien Grenier

Reputation: 3394

You can use the built-in filter function.

print filter(lambda word: len(word) == N, F)

Upvotes: 0

kll
kll

Reputation: 111

Although this is "inferior" in terms of code size and overall elegance to the other answers, its resemblance to the original code might help in understanding the faults of that implementation.

F=['MIKE', 'BALL', 'FISH', 'BAT', 'BEAR', 'CAT', 'AT', 'ALLY']

number=input("How long would you like your word to be?")
possible_words=[]
for word in F:
    if len(word) == number:
        possible_words.append(word)

To check the length of a string, you use len(string) and not string(len). possible_words is a list and to add an element to it, you use .append() and not +=. += can be used to increase a number or add a single character to a string. Remember to use double equals (==) and not single (=) when doing comparisons.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251001

You can also use filter here :

 filter(lambda x:len(x)==number, F)

help(filter):

In [191]: filter?
Type:       builtin_function_or_method
String Form:<built-in function filter>
Namespace:  Python builtin
Docstring:
filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.

Upvotes: 2

mgilson
mgilson

Reputation: 309969

This will give you a list of words whose length is N

possible_words = [x for x in F if len(x) == N]

Note that you have a list, not a dictionary

Upvotes: 6

Related Questions