Python Forum
Multiple Loop Statements in a Variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple Loop Statements in a Variable
#1
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
Reply
#2
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.
Dexty likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable definitions inside loop / could be better? gugarciap 2 441 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,725 Nov-07-2023, 09:49 AM
Last Post: buran
  Multiple variable inputs when only one is called for ChrisDall 2 491 Oct-20-2023, 07:43 PM
Last Post: deanhystad
  Trying to loop through code to plot seaborn line plots across multiple subplots eyavuz21 0 1,680 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,591 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  loop (create variable where name is dependent on another variable) brianhclo 1 1,140 Aug-05-2022, 07:46 AM
Last Post: bowlofred
  Multiple user defined plots with secondary axes using for loop maltp 1 1,451 Apr-30-2022, 10:19 AM
Last Post: maltp
Big Grin Variable flag vs code outside of for loop?(Disregard) cubangt 2 1,175 Mar-16-2022, 08:54 PM
Last Post: cubangt
  How to save specific variable in for loop in to the database? ilknurg 1 1,150 Mar-09-2022, 10:32 PM
Last Post: cubangt
  How to add for loop values in variable paulo79 1 1,450 Mar-09-2022, 07:20 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020