Search code examples
pythonloopstry-catchexcept

Please write this loop and try/except in one line with python


How can I condense this code into a single line? Thanks for the help.

for query in announcements:
    try:
        query.price = int(query.price)
        listme.append(query.price)
    except:
        print(listme)

Solution

  • This will basically do the same thing, without the printing of failure:

    listme.extend(int(query.price) for query in announcements if query.price.isdigit())
    

    This assumes that query.price is a string and that listme is an existing list.

    Trying to print the failures as well would be tricky (and unreadable) but possible:

    listme.extend(x for x in [int(query.price) if query.price.isdigit() else print(query.price) for query in announcements] if x is not None)
    

    Unless this is a homework assignment or something, it's generally very bad practice to insist that your code fits in one messy unreadable line, so don't do it