Home > Mobile >  How do i sum two lists in this case?
How do i sum two lists in this case?

Time:01-12

from random import randrange

n = int(input("Enter the number of throws: "))

throw1 = []
throw2 = []


for i in range(n):
    throw1.append(int(randrange(1,7)))
    throw2.append(int(randrange(1, 7)))

final_throw = sum(throw1, throw2)

print(throw1,throw2)

I want to sum throw1 and throw2 together but I don't know how(this is not working).

My issue is quite easy to solve but as a beginner I dont see the solution. Please can you help me ?

CodePudding user response:

If you want a global sum, you can concatenate lists

>>> sum(throw1   throw2)
38

If you want to sum pairwise element, use a comprehension:

>>> [sum(x) for x in zip(throw1, throw2)]
[6, 4, 4, 6, 5, 4, 9]

Input:

>>> throw1
[2, 3, 1, 4, 3, 1, 6]

>>> throw2
[4, 1, 3, 2, 2, 3, 3]

CodePudding user response:

In this case , you can use final_throw = sum(throw1 throw2)... It will add throw2 after throw1 in a random order . The output will be Enter the number of throws: 3 [2, 1, 1] [5, 6, 3]

Here numbers in list are random.

CodePudding user response:

You can consider the below approach.

import os

throw1 = [1, 2, 3, 4, 5]
throw2 = [10, 11, 12, 13, 14]
lists = zip(list1, list2) 
final_throw = [x   y for (x, y) in lists]
print(final_throw)
  • Related