Home > Software engineering >  elements to python list
elements to python list

Time:12-23

iterating and appending a list to another list but printing unexpected output: what is wrong? the last output contains the same elements overwriting the appended elements at each iteration.

def pascal(n):
    """
    print pascal triangle
    """
    list = []
    if (n > 0):
        lst = []
        for line in range(1, n   1):
            k = 1
            lst.clear()
            for i in range(1, line   1):
                lst.append(k)
                k = int(k * (line - i)/i)
            print(lst)
            list.append(lst)
        print (list)
    else:
        print (list)

pascal(5)

**output:**
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[[1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1]]
**expected output:**
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[[1,], [1, 1], [1, 2, 1], [1,  3, 3, 1], [1, 4, 6, 4, 1]]

CodePudding user response:

Create a new list on each iteration instead of mutating the same one each time.

res = []
if n > 0:
    for line in range(1, n   1):
        k = 1
        curr = []
        for i in range(1, line   1):
            curr.append(k)
            k = int(k * (line - i)/i)
        print(curr)
        res.append(curr)
print(res)

CodePudding user response:

def pascal(n):
    """
    print pascal triangle
    """
    lis = []
    if (n > 0):
        lst = []
        for line in range(1, n   1):
            k = 1
            lst.clear()
            print(lst,lis) # This is what happening .. your result lis is become empty while you trying to clear lst..! and in the last lst contains value are stored in all the list of lists.
            for i in range(1, line   1):
                lst.append(k)
                k = int(k * (line - i)/i)
            #print(lst)
            lis.append(lst)
        #print(lis)
    else:
        print(lis)
pascal(5)

Output:-

[] []
[] [[]]
[] [[], []]
[] [[], [], []]
[] [[], [], [], []]

Reason. In above code list of lists reference the same object. This is because of the fact that lists are referential structures in python. when the last loop iterates lsi store the value in lis in all list of lists..

You can do..

def pascal(n):
    """
    print pascal triangle
    """
    lis = []
    if (n > 0):
        for line in range(1, n   1):
            lst = []
            k = 1
            for i in range(1, line   1):
                lst.append(k)
                k = int(k * (line - i)/i)
            print(lst)
            lis.append(lst)
        print(lis)
    else:
        print(lis)

pascal(5)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

also not initalise list with a name list as it is a built-in data type..!

  • Related