Jake Z
Jake Z

Reputation: 13

Add two list of integer

Python beginner here! I want do a nested for loop to add two integer list. But somehow I can't get last index of list. Could anyone help please?

num_cases = [500, 800, 900, 1000]
num_predic = [10, 20, 30]
predict( num_predic,num_cases)
def predict(cases, predicted_growths):
    new_cases = []
    for elem in range(len(predicted_growths) + 1 ):
        for elems in range(len(cases)):
            grow = cases[elem] + predicted_growths[elems]
            new_cases.append(grow)
            if len(new_cases) == len(cases):
                new_cases.insert(len(new_cases),predicted_growths[-1] + cases[-1])
                #Since I don't know how to reach the last 
                #index of list. Then I found out insert() method. Still doesn't work it will 
                #print same value three times.
                print(new_cases)
                new_cases = []
                break

my output:

[510,810,910]
[520,820,920]
[530,830,930]

output suppose look like this:

[510,810,910,1010]
[520,820,920,1020]
[530,830,930,1030]
       

Thank you so much for help!

Upvotes: 0

Views: 88

Answers (2)

Gannon
Gannon

Reputation: 78

Just to make it really simple, Tim Roberts answer being good, this is the same but maybe easier to understand for a beginner.

num_cases = [500, 800, 900, 1000]
num_predic = [10, 20, 30]

for np in num_predic:
    row=[]
    for nc in num_cases:
        row.append(np+nc)
    print(row)

Output is:

[510, 810, 910, 1010]
[520, 820, 920, 1020]
[530, 830, 930, 1030]

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54698

You're making this too hard.

num_cases = [500, 800, 900, 1000]
num_predic = [10, 20, 30]
def predict(cases, predicted_growths):
    for predic in predicted_growths:
        new_cases = [case+predic for case in cases]
        print(new_cases)

predict(num_cases, num_predic)

Now, there are better ways to do this, but this show you the keys. Don't worry about indices. Just enumerate the values.

At least one person has tried to edit this to swap the loops. Don't do that. What I have here is correct. Output:

[510, 810, 910, 1010]
[520, 820, 920, 1020]
[530, 830, 930, 1030]

Upvotes: 1

Related Questions