Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

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)

Update:

Click on show more to see the code.

2 Answers

Relevance
  • 7 years ago
    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_introspecti...

    Also filter..

    http://docs.python.org/2.7/library/functions.html#...

  • Anonymous
    7 years ago

    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

Still have questions? Get your answers by asking now.