0

I am in the process of learning Python. I came across a review question and am having some trouble understanding the notation of how a variable is declared. Below is the variable:

t = [[3-i for i in range(3)] for j in range(3)]

I am familiar with the range function but am unsure with the above notation. My assumption of what is happening is the variable t has a nested for loop. I am more familiar with the following notation:

for i in range(3):
  for j in range(3):
      # some code

but I am unsure how the first part of the variable 3-i plays a factor in this. Any advice would be helpful.

Imran Sandozi
  • 235
  • 1
  • 3
  • 11
  • 2
    your assumption is correct , and its called `list comprehension` – eshirvana Feb 07 '22 at 01:04
  • How about you run the code and observe the results? The result would give you a better understanding! – Irfanuddin Feb 07 '22 at 01:04
  • 1
    You have your nested for loops in reverse. It's creating a list of `3-i` for each `i`, and then repeating that list for each `j`. Also, if it helps, you can think of `3-i` as `(3-i)` which is basically just the value. – Gino Mempin Feb 07 '22 at 01:07
  • 3
    Does this answer your question? [List comprehension on a nested list?](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list) (particularly, this answer https://stackoverflow.com/a/46611767/2745495 which describes the equivalent for-loops) – Gino Mempin Feb 07 '22 at 01:09
  • See also https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ – Karl Knechtel Feb 07 '22 at 01:16

0 Answers0