Python Forum

Full Version: Multiple Loop Statements in a Variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm quite familiar with:
for i in range(n):
	for j in range(n):
		print(i, j)
and
myVar = [i for i in range(n)]
Is there a way to correctly do the last example with 2 variables? Like this:
myVar2 = [i, j for i in range(n) for j in range(n)]
myVar2 returns a
Error:
SyntaxError: invalid syntax
Fine, except you need to place a single object in the list, so put parentheses around the tuple for the parser to understand that.

>>> [(i, j) for i in range(3) for j in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
That said, for this specific case I would probably prefer to use itertools.product.