Kirsty
Kirsty

Reputation: 13

Adding together elements contained in two lists

I am trying to add elements of two lists together e.g. listing all integers below 10 that are multiples of 3 or 5. The sum of these multiples should be 23 (3+5+6+9) but I keep getting 18. I have only just starting programming and learning python. Here's my code:

for i in range (1,10):
    if i % 3 == 0:
        print(i)
for x in range (1,10):
    if x % 5 ==0:
        print(x)
sum_multiples=i+x
print(sum_multiples)

Upvotes: 1

Views: 36

Answers (3)

Brady Gho
Brady Gho

Reputation: 53

First off, let me address your problem. When you add variable i and variable x, they are both value of 9. This is because after the loop their value is 9, and because you are adding the values after the loop, you are adding 9 + 9.

You can fix this by making a variable outside the loop and adding the number to the variable. My code would be:

total = 0
for i in range (1,10):
    if i % 3 == 0:
        print(i)
        total = total + i
for x in range (1,10):
    if x % 5 ==0:
        print(x)
        total = total + x

print(total)

(this is just based off what you were doing, I would probably condense it into one loop)

Upvotes: 0

qmeeus
qmeeus

Reputation: 2402

What you are trying to do:

3 + 6 + 9 + 5 = 23

What you are doing:

9 + 9 = 18

This is what you want:

l1 = [x for x in range(1, 10) if x % 3 == 0]
l2 = [x for x in range(1, 10) if x % 5 == 0]
print(sum(l1) + sum(l2))

Upvotes: 1

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

You could so something like this:

sum_multiples = 0
for i in range(1, 10):
    if i % 3 == 0 or i % 5 == 0:
        sum_multiples += i
print(sum_multiples)

If you prefer a one line solution:

print(sum(i for i in range(1, 10) if i % 3 == 0 or i % 5 == 0))

Upvotes: 0

Related Questions