Search code examples
pythonlistloopsnested-loopsnested-lists

I would expect the output to be like [[1,2,3,4,5,6,7,8,9,10],[2,4,6,8,10,12...18,20],[3,6,9...27,30].....[9,18,27..90]]


I'm using python.I need to get output as I mention in bottom. This is the way I try.

 L = [i for i in range(1,11)]
    print(L)
    p = []
    p.extend(L for _ in range(10))
    #print(p)
    for _ in range(10):
        for i in range(10):
            p[_][i] = (_+1)*p[_][i]
    print(p)
and this is the output I got.

Output:[[3628800, 7257600, 10886400, 14515200, 18144000, 21772800 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000], [3628800, 7257600, 10886400, 14515200, 18144000, 21772800, 25401600, 29030400, 32659200, 36288000]]

I would expect the output to be like

[[1,2,3,4,5,6,7,8,9,10],[2,4,6,8,10,12...18,20],[3,6,9...27,30].....[9,18,27..90]]

Solution

  • There are several problems: Do not use _ as a variable name it's for variables you won't reuse.

    You are getting this problem because of this line:

    p.extend(L for _ in range(10))
    

    p is a list of references to L. So when you do:

    p[_][i] = (_+1)*p[_][i]
    

    you modify L, and thus all the lists in p.

    Your code fixed:

    p = []
    p.extend(list(range(1,11)) for _ in range(10))
    
    for i in range(10):
        for j in range(10):
            p[i][j] = (i+1)*p[i][j]
    print(p)
    

    However, there is a simpler way to do it:

    p  = [ list(range(i, i*11, i )) for i in range(1,10)]