Search code examples
pythonnested-loops

How to generate skewed 2d loop in python


How to generate this loop in python syntax:

for (int i = 0; i < 10; i++)
    for (int j = 0; j <= i; j++)
        (...)

Of course, this works:

for i in range(10):
    for j in range(10):
        if j > i: continue
        print((i,j))

But is there a more elegant way to say let j be less or equal to i in one line?


Solution

  • Ok adding my comment as an answer, with a correction (for j in range(i+1) instead of for j in range(i)):

    for i in range(10):
        for j in range(i+1):
            print(f'i: {i}, j: {j}')
    

    Does this help you?