Suppose I’ve got a list l = [1,2,3]
and I want to create a set of all numbers in that list and their squares. Ideally, in a single comprehension expression.
Best I can come up with is (two iterations over the list):
set(_ for _ in l).union(_ * _ for _ in l)
Your own code can be shortened to:
set(l).union(x**2 for x in l)
in which I renamed _
to x
, because _
indicates the value is not important, but it is.
Strictly speaking you're still iterating over the list
twice, but the first time implicitly.
If you insist to iterate once, you'd get this:
{y for x in l for y in (x, x**2)}
which is a double comprehension that encompasses the following:
result = set()
for x in l:
for y in (x, x**2):
result.add(y)