Search code examples
pythonlistnested-loops

2d list with a compact nested loop


I've recently started learning python and have stumbled in a syntax dilemma. Is there a way to do what this pice of code does:

def crescentOrderArray1(rows, columns):
    arr = [[] for i in range(rows)]
    count = 1
    for row in range(rows):
        for colum in range(columns):
            arr[row].extend([count])
            count = count + 1
    return arr 

with a discreet syntax like

def crescentOrderArray2(rows, columns):
    count = 1
    arr = [[count for i in range(rows)] for i in range(rows)]
    return arr 

I've tried modifying the "count" statement in "crescentOrderArray2", but with no success. I was expecting a way iterate each time it adds a "count"


Solution

  • try this, it's the most compact way:

    def crescent_order_array(rows, columns):
        return [[i+j for i in range(1, columns+1)] for j in range(0, rows*columns, columns)]