how do i add this list together? I keep on getting an error

Question:

import re
def ReadText()

    total = 0
    text_file = open('Heliatext.txt', 'r')
    lines = text_file.read()
    numblist = []
    print(lines)
    print(len(lines))
    stuff = re.findall(r'd+', lines)
    numblist.append(stuff)
    print(numblist)
    for x in numblist:
        total += x
        print (total)

    text_file.close()
ReadText()

Hi all, so i’m trying to scrape a simple text file for integers, put them into a list, and then add them all together. I’ve been looking throughout stackoverflow for how to do this and as far as i can tell, this way should work but i keep on getting this error

Traceback (most recent call last): File
“C:/Users/chris/Desktop/Helia.py”, line 32, in
ReadText() blah blah, 1 File “C:/Users/chris/Desktop/Helia.py”, line 28, in ReadText
total += x TypeError: unsupported operand type(s) for +=: ‘int’ and ‘list’

file contents are this:

blah blah, 1
this is in he3lia’s file
6

Any help and insight is appreciated. You guys are awesome!

Asked By: Cflux

||

Answers:

You need to convert the entries of your list to integer.
try this instead:

for x in stuff:
    total += int(x)
Answered By: python novice

re.findall returns strings, so you’ll need to coerce the numeric strings to ints. Python’s strong typing won’t let you add strings together.

You’ve got some delightful Python discoveries ahead of you! Your 6 lines of iterative code starting stuff = re.findall(...) and finishing print (total) can be written in two lines in Python:

numblist = [int(num) for num in re.findall(r'd+', lines)]
print(sum(numblist))

Have a read about comprehensions in Python to find out more.

Answered By: Nic

There are two problems here: (1) numblist is a list of lists, rather than a flat list, and (2) the list values are strings rather than integers.

You can fix the first problem by using the extend method rather than the append method. You can also use += to do the same thing.

You can fix the second problem by converting the strings to integers, i.e. use int(x) rather than x.

Here’s is an updated version of the posted code that fixes these problems:

import re

def ReadText():
    total = 0
    text_file = open('Heliatext.txt', 'r')
    lines = text_file.read()
    numblist = []
    print(lines)
    print(len(lines))
    stuff = re.findall(r'd+', lines)
    numblist.extend(stuff)
    print(numblist)
    for x in numblist:
        total += int(x)
        print (total)
    text_file.close()

ReadText()
Answered By: Tom Karzes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.