Home > database >  Python looping questions
Python looping questions

Time:10-14

def up_to_keyword(items: list[str], keyword: str) -> list[str]: """Return a new list that contains only the items that occur before keyword in items, or all items if keyword is not an element of items. Do not include keyword in your result.

>>> up_to_keyword(['red', 'orange', 'yellow', 'green', 'blue'], 'yellow')
['red', 'orange']
>>> up_to_keyword(['some', 'body', 'once', 'told', 'me'], 'world')
['some', 'body', 'once', 'told', 'me']
"""

What is the return statement for this function?

CodePudding user response:

You can use itertools.takewhile with the keyword's inequality method as the predicate:

from itertools import takewhile

def up_to_keyword(items, keyword):
    return list(takewhile(keyword.__ne__, items))

Demo: https://replit.com/@blhsing/RevolvingUnitedBlock

CodePudding user response:

Solution:

def up_to_keyword(items: list[str], keyword: str) -> list[str]:
    if keyword in items:
        index = items.index(keyword) # Find index
        return items[:index] #return items before index
    return items

Output

>>> up_to_keyword(['red', 'orange', 'yellow', 'green', 'blue'], 'yellow')
    ['red', 'orange']
>>> up_to_keyword(['some', 'body', 'once', 'told', 'me'], 'world')
    ['some', 'body', 'once', 'told', 'me']
  • Related