Amir Mohammad
Amir Mohammad

Reputation: 3

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)

Upvotes: 0

Views: 73

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11932

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

Upvotes: 2

Related Questions