0

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)
2
  • Do you have a shortage of newline characters in your environment? Commented Nov 24, 2019 at 8:00
  • @Derlin Surprisingly, it can be done. See Ofer Sadan's answer. Commented Nov 24, 2019 at 8:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

parse_float = lambda x, y=exec("def f(s):\n try:\n return float(s)\n except: return None"): f(x)
If query.price is float within string literals, it fails.
@SayandipDutta the code in the question would fail as well. This is equivalent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.