0

I am familiar with for loops on a basic level. I use them quite often at school, but I just came across one online that I do not understand. I was wondering if someone could possibly explain to me what kind of loop this is or if you could even tell me what type of loop it is. I am willing to research it on my own, but am not finding anything. The loop is below and can be found here.

for i,j in [(i,j) for i in range(len(rows)-2,-1,-1) for j in range(i+1)]:
    rows[i][j] +=  max([rows[i+1][j],rows[i+1][j+1]])
cvnntg
  • 334
  • 2
  • 9
  • It's a list comprehension. – Blender Dec 30 '13 at 05:49
  • 4
    poorly written mix a for loop and a list comprehension –  Dec 30 '13 at 05:50
  • It loops the rows bottom-up and add to each element the maximum between the two items below it, hence the final result will be in `rows[0][0]` (the first row which holds only a single item). This is not a poor implementation but rather a clever one, which belongs [*here*](http://codegolf.stackexchange.com/) – Nir Alfasi Dec 30 '13 at 06:02
  • @alfasin I understood how the for loop worked from his explanation of it on the link provided. I just did not understand the syntax of the for loop provided. icktoofay's answer below helped me a lot though. Thank you, all. – cvnntg Dec 30 '13 at 06:04
  • @alfasin (and others) Consider posting revised versions of your comments as answers. – Steinar Lima Mar 28 '14 at 12:34
  • possible duplicate of [python list comprehension explained](http://stackoverflow.com/questions/20639180/python-list-comprehension-explained) – Martijn Pieters Mar 28 '14 at 15:17

2 Answers2

2

That's a loop over a list comprehension. It could roughly be translated as:

temp = []
for i in range(len(rows) - 2, -1, -1):
    for j in range(i + 1):
        temp.append((i, j))
for (i, j) in temp:
    rows[i][j] += max([rows[i + 1][j], rows[i + 1][j + 1]])

Or, more directly:

for i in range(len(rows) - 2, -1, -1):
    for j in range(i + 1):
        rows[i][j] += max([rows[i + 1][j], rows[i + 1][j + 1]])
icktoofay
  • 126,289
  • 21
  • 250
  • 231
0

The part in the [ ... ] is called a List Comprehension it produces a List.

Don't think this code is good code, it isn't a good example of maintainable code.