Python: Given a list of words, remove those with more than four characters?

Help answer this question:

def remove_long_words(words):
"""Given a list of words, remove any that are longer
than four letters and return a new, shorter list.

>>> w = ['ten', 'one', 'seven', 'nine', 'fifteen']
>>> remove_long_words(w)
['ten', 'one', 'nine']
>>> w = ['fifteen']
>>> remove_long_words(w)
[]
>>> w = ['ten', 'one', 'nine', 'six']
>>> remove_long_words(w)
['ten', 'one', 'nine', 'six']
>>> remove_long_words(['ten']) == ['ten']
True
"""

(replace this line with your code)

2014-03-23T21:09:22Z

Click on show more to see the code.

Herp-da-Derp2014-03-24T08:15:28Z

Favorite Answer

1. Initialise a variable bigWords to be an empty list
2. iterate through the list of words
2.2 if current word is bigger than four (Hint: use len function) append to bigWords
3. Return bigWords

There are better methods.
Check out list comprehension: http://www.diveintopython.net/power_of_introspection/filtering_lists.html
Also filter..
http://docs.python.org/2.7/library/functions.html#filter

Anonymous2014-03-24T21:33:34Z

def remove_long_words(lwords):
## lwords == list of words

for elem in lwords:
if len(elem) > 4:
## if pop at the index of the element location
lwords.pop(lwords.index(elem))

return lwords