ReubenConroy
ReubenConroy

Reputation: 5

Adding elements of two lists

I'm trying to add two lists in python. The first list has the results of the first test and the second list the second, I'm trying to make another list with the total marks in it. Heres my code:

import csv

with open ("UASHSDDP3efiles.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    list1 = []
    for row in reader:
        list1.append(row[1])
    print (",".join(list1))

with open ("UASHSDDP3efiles.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    list2 = []
    for row in reader:
        list2.append(row[2])
    print(",".join(list2))

list3 = [(x + y) for x, y in zip(list1, list2)]
print (list3)

So far for the output all i get is:

>>> 55,25,40,21,52,42,19,47,37,40,49,51,15,32,4
51,36,50,39,53,33,40,57,53,34,40,53,22,42,13
['5551', '2536', '4050', '2139', '5253', '4233', '1940', '4757', '3753', '4034', '4940', '5153', '1522', '3242', '413']

Upvotes: 0

Views: 128

Answers (2)

Prashant Yadav
Prashant Yadav

Reputation: 551

That's because your list1 and list2 contains elements of string type and the elements are getting concatenated instead of getting added.

Therefore you should either convert elements to int before appending them to your lists or explicitly convert all elements to int by traversing the whole list again

Upvotes: 1

enrico.bacis
enrico.bacis

Reputation: 31524

You are adding two strings, that's why '55' + '51' = '5551'.

Cast them to integers in order to sum the two numbers:

list3 = [(int(x) + int(y)) for x, y in zip(list1, list2)]

Upvotes: 0

Related Questions