Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I put a break in a single-line for loop

I am working on a discord bot and returning a list of item. Unfortunately, if the list exceeds 25 items, it throws an error. I want break the loop after 25 loops. Below is a sample of code provided in the discord.py documentation; the for loop is a single line and does not work if I try to modify it:

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower()
    ]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use the itertools.islice to take first N results from a generator (...):

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> Iterable[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return itertools.islice(
        (app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower())
    , 25)

If desiring a List as result, wrap above return with list(...).


With just a list, slice with [:N]:

async def fruit_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    current = current.lower()
    return [app_commands.Choice(name=f, value=f)
            for f in fruits if current in f.lower()][:25]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading