Jovid Nurov
Jovid Nurov

Reputation: 31

How should I append all my results to one list after each iteration in the python?

def pascalstriangle(n):
    list = [1]
    for i in range(n):
        print(list)
        newlist = []
        newlist.append(list[0])
        for i in range(len(list) - 1):
            newlist.append(list[i] + list[i + 1])
        newlist.append(list[-1])
        list = newlist
print(pascalstriangle(3))

I want to see this print format [1,1,1,1,2,1] instead of

[1] 
[1, 1]
[1, 2, 1]

Upvotes: 0

Views: 50

Answers (3)

niraj
niraj

Reputation: 18208

To fix the above code, whenever you are printing list you can add those to other list (in below code adding them to final_list with extend) and finally return it at end of the function:

def pascalstriangle(n):
    list = [1]
    final_list = []

    for i in range(n):
        final_list.extend(list)
        newlist = []
        newlist.append(list[0])
        for i in range(len(list) - 1):
            newlist.append(list[i] + list[i + 1])
        newlist.append(list[-1])
        list = newlist
    return final_list

print(pascalstriangle(3))

Result:

[1, 1, 1, 1, 2, 1]

One thing you may want to consider is not using list as variable and using somethin like my_list.

Upvotes: 1

Vipin Joshi
Vipin Joshi

Reputation: 302

Just merge two lists :

final_list = list1 + list2

Upvotes: 0

algrice
algrice

Reputation: 229

You can combine two lists in Python like this:

print([1, 2] + [3])
> [1, 2, 3]

I hope that helps!

Upvotes: 0

Related Questions