0

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']
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
  • 2
    That output does appear to be the combination of your two lists; "55" and "51" make "5551", and so on. Is that not what you want? What output are you expecting to get? – Kevin Dec 10 '15 at 12:58
  • In addition to the correct answers you've got, if you want to write the list of sums to an external file remember to convert the `int`s in `list3` back to strings... – gboffi Dec 10 '15 at 14:01

2 Answers2

1

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

Prashant Yadav
  • 531
  • 2
  • 9
  • 25
0

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)]
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
  • Thanks for the answer, If you don't mind im also curious why ( http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list ) doesn't work for me? The question asked is the same as mine yet the correct answer doesn't seem to be the correct answer. – ReubenConroy Dec 11 '15 at 09:17
  • @ReubenConroy: In that question they are using arrays of integers. You are reading a file, so it reads it as a string; when you use the method `split` on a string, it creates an array of strings, so you don't have `[1,2,3]` but `['1', '2', '3']`. When you use the operator `+` on two strings it concatenates them. – enrico.bacis Dec 11 '15 at 09:53