On Sep 21, 2019, at 01:03, 보성 최
How about allowing to create multiple items for each loop in comprehension? I'm not sure this grammar is available, though.
for example:
[loop for set] s = set() for i in range(10): s.add(i) s.add(i * 10) [current comprehension] s = { x for i in range(10) for x in (i, i * 10) }
Is there a reason it has to be a single comprehension? I think this would be a lot more readable: s = {x for x in range(10)} | {x*10 for x in range(10)} This doesn’t work as well for list comprehensions, or generator expressions, but it’s still not too horrible with a trivial interleave (flattened-zip) function: it = interleave((x for x in range(10)), (x*10 for x in range(10))) Which brings up another possibility: just build tuples and flatten: s = set(flatten((x, x*10) for x in range(10)) If you want, you could even make that a single flatten-and-setify function: def fset(It): return { x for tup in it for x in tup } s = fset((x, x*10) for x in range(10)) That’s still not quite as readable as your suggestion, but it’s not that bad, and it’s already available.
[suggested comprehension] s = { i, i * 10 for i in range(10) }
I think you could find a way to make this not ambiguous as far as the parser is concerned, but it might be confusing for human readers. Remember that you can have a tuple as the yield expression, or you could have i as one element and a generator expression as the second, and possibly other things. I think all such other things would require an extra set of parens in every possible case, so the parser doesn’t have to do any extra look ahead or anything, but I think most humans don’t internalize the exact rules for when tuples do and don’t require parens, etc.