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
?