Can't get the walrus operator to work (Python double list comprehension)

314 views Asked by At

This list comprehension does not work:

buy_prices = [(buylow := round(0.997 + ii/10000.0, 5), max(jj, buylow)) for jj in [buylow, 0.9982] for ii in range(21)]

NameError: name 'buylow' is not defined

This one doesn't either:

buy_prices = [(buylow, max(jj, buylow)) for jj in [buylow := round(0.997 + ii/10000.0, 5), 0.9982] for ii in range(21)]

SyntaxError: assignment expression cannot be used in a comprehension iterable expression

How am I supposed to do this? Or do I just have to do the round calculation for buylow twice?

1

There are 1 answers

4
Justin Furuness On

I'd highly recommend not using nested list comprehensions, since that is not very readable to many people.

Instead maybe something like this:

buy_prices = list()
for ii in range(21):
    buylow = round(.997 + ii / 10000, 5)
    for jj in (buylow, .9982):
        buy_prices.append((buylow, max(jj, buylow))