0

while trying to print multiple rows and columns using list comprehensions, the following code works

X=[[x for x in range(y)] for y in range(3)]

but this code does not work

X=[x for x in range(y) for y in range(3)]

What difference it makes when list is used instead of direct loop. Generally for multiple loops it works from left to right. in this case the loops are working from right to left so we able to use y before y is declared in for .

user2779311
  • 1,688
  • 4
  • 23
  • 31
  • in this line `X=[x for x in range(y) for y in range(3)]` you got error not define `y` you can write like below but your output different: `X=[[x] for y in range(3) for x in range(y) ]` – I'mahdi Sep 01 '21 at 05:58
  • In addition to the linked duplicate, please try https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ . Or try [copying and pasting your planned question title into a search engine](https://duckduckgo.com/?q=how+multiple+list+comprehension+works), which gives multiple high-quality results off the top. You have multiple gold badges and your account is almost 8 years old; you should know these techniques and [expectations](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) by now. – Karl Knechtel Sep 01 '21 at 05:58
  • ... In fact, when I try that search query, one of the things I find is *you asking this same question less than a day ago, and getting it closed with the same duplicate link*. – Karl Knechtel Sep 01 '21 at 06:00
  • @KarlKnechtel i had gone through the link marked but could not find answer to my query. since that question was closed for answers i had to post new one. i wanted to know how working of list comprehension differs when i put list on the inner for loop. then it works from right to left otherwise it works from left to right. – user2779311 Sep 01 '21 at 06:14
  • The linked duplicate explains exactly what happens. You apparently already understand what output you get from the code. "How the working differs" isn't a meaningful question. If you want to see how it's implemented, the source code is available. If you want to know why it's defined to work that way, you should ask the people responsible. – Karl Knechtel Sep 01 '21 at 06:19
  • As a general rule, if you find it hard to make a list comprehension, it's time to change it to a loop. – BoarGules Sep 01 '21 at 06:52

1 Answers1

1

For nested list comprehension iterating from left to right is okay, because it iterates y first before x.

But without it it needs to be from right to left, because this way it would say y is not defined because Python runs from left to right.

So try:

X = [x for y in range(3) for x in range(y)]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114