Search code examples
pythonarraylistnested-for-loop

How to turn a nested for loop into a 2D list or array


I want to ask a question about nested loops. I have a for-loop like this:

for x in range(1,5):
    for y in range(1,5):
        z =10
        print(x,y,z)

I have tried this:

list = []
for x in range(1,5):
    nested = []
    for y in range(1,5):
        z = 10
        nested.append(y)
    list.append(nested)

but this doesn't give me the output I want

I'd like to turn the nested for loop into a 2D list(array) to be like this:

Output:

[[1,1,10],[1,2,10],[1,3,10],[1,4,10],[2,1,10],[2,2,10].....,[4,4,10]

Solution

  • z = 10
    result = []
    for i in range(1,5):
        for j in range(1,5):
            result.append([i,j,z])
    

    or as a list comprehension

    result = [[i,j,10] for i in range(1,5) for j in range(1,5)]