0

I've had a look through the "similar questions" section as well as searching the site, but unfortunately I couldn't find what I'm looking for.

Unimportant preface:

I'm working on a function that takes in value and base as integers and returns value rewritten in the specified base. eg baseFunc(10,2) will return '1010'

For readability, here's a copy that doesn't bother with latin characters

Code:

digits = [[value%base, value:=value//base][0] for _ in range(value) if value]

Expectation Vs Outcome:

I expected this syntax to enact a break on the loop when value reaches 0, however instead it iterates value number of times, and only appends an item if value:=value//base is yet to reduce value to 0.

This behavior seems quite obvious now that I know.

What I Need For Expected Functionality:

I would like to know how to enact break from inside a list comprehension based on some if statement, if it's even possible. I'm 100% okay with hacky alternatives as this project will never be in production.

Could I just use a for loop and the .append() built in? Absolutely, but I would still like to know.

TL;DR:

What list comprehension syntax would be equivalent to if criteria: break?

  • 1
    Does this answer your question? [Using break in a list comprehension](https://stackoverflow.com/questions/9572833/using-break-in-a-list-comprehension) – luuk Mar 16 '21 at 18:07
  • Maybe you can use [`itertools.takewhile`](https://docs.python.org/3/library/itertools.html?highlight=filterfalse#itertools.takewhile). – Matthias Mar 16 '21 at 18:09
  • Short answer is genexpr + `itertools.takewhile` (which wraps which depends on whether the condition is based on the inputs or the outputs) that you `list`ify. – ShadowRanger Mar 16 '21 at 18:10
  • add condition with `if` to statement – Vova Mar 16 '21 at 18:10
  • 1
    @Vova That won't stop the iteration. – Matthias Mar 16 '21 at 18:11
  • @Matthias of course, but list comprehension is for building iteration, not for searching data – Vova Mar 16 '21 at 18:17

0 Answers0